Search code examples
c#filesystemwatcher

FileSystemWatcher - Create and Rename C#


I'm currently working on a feeder app which looks for new files added and print me the name of it. But when I create a new file, the file name is printed immediately on the console. It is not waiting till I rename the newly created file. How can I do this?

Below are my settings. I didnt use watcher.Renamed+=OnRenamed because when I rename the any other file which is in the folder it is printing on the console. But my requirement is only show the list of newly created files.

 watcher = new FileSystemWatcher(folderPath);
 watcher.IncludeSubdirectories = true;
 watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
 watcher.Filter = "*.*";
 watcher.Created += OnCreated;

TIA


Solution

  • The problem is (probably) that you're going into windows explorer, right clicking and selecting new -> file type. When you do that, windows immediately creates the file with a default name like New Text Document.txt and give you an opportunity to rename it. This rename that follows in indistinguishable from any other rename so you have 2 options.

    1. Stop creating files like that, rather create files by opening a text editor (or whatever app you're using word, excel etc) create a new file in the app and save it with the correct name. That will create the file with the name you expect.
    2. Change your code to cater for file renames.