25

So far I know that FileSystemWatcher can look into a folder and if any of the files inside that folder is changed,modifies,.etc... then we can handle it. But I am not sure which filter and event I should use in my scenario: Watch for a Folder, If a file is added to that folder, do XYZ ... So In my scenario I don't care if an existing file is changed,etc..those should be ignored...only do XYZ if and only if a new file has been added to that Folder...

Which event and filter do you recommended for this scenario?

Bohn
  • 26,091
  • 61
  • 167
  • 254

2 Answers2

15

Set up the watcher:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "Blah";

watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
    | NotifyFilters.FileName;

watcher.Created += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEvents = true;

Then implement the FileCreated delegate:

private void OnChanged(object source, FileSystemEventArgs e) {
    Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}
Chris Nolet
  • 8,714
  • 7
  • 67
  • 92
David Brabant
  • 41,623
  • 16
  • 83
  • 111
  • 6
    Why would we set the `NotifyFilter` if we only care about a file being created, not changed? – Jeff B May 21 '13 at 19:33
  • 10
    @JeffBridgman It's not intuitive, but the NotifyFilter serves as a way to fine tune the notifications coming from FileSystemWatcher. By default, NotifyFilter is set to DirectoryName | FileName | LastWrite. These give you the ability to pick up on the core file activities you'd expect from FileSystemWatcher: Created, Changed, Deleted, and Renamed. Notify Filter can be altered to increase the spectrum of file/directory attributes that will be monitored and used as input to trigger the various events. Although, as you can surmise, most of the other filters will only result in a Changed" event. – CobaltBlue Feb 28 '14 at 02:06
2

Please look here for a detailed explanation of the FileSystemWatcher: http://www.c-sharpcorner.com/uploadfile/mokhtarb2005/fswatchermb12052005063103am/fswatchermb.aspx

You will have to look for created files if you want to look for added files.

You specify the type of change to watch for by setting the value of a WatcherChangeType enumeration. The possible values are as follows:

  • All: The creation, deletion, change, or renaming of a file or folder.
  • Changed: The change of a file or folder. The types of changes include: changes to size, attributes, security settings, last write, and last access time.
  • Created: The creation of a file or folder.
  • Deleted: The deletion of a file or folder.
  • Renamed: The renaming of a file or folder.

Also you may just wire up the event handler that fires if a file is created (added) and not implement all the other events since they are not interesting for you:

watcher.Created += new FileSystemEventHandler(OnChanged);
jrouquie
  • 4,315
  • 4
  • 27
  • 43
Jason De Oliveira
  • 1,732
  • 9
  • 16