Pages

Wednesday, May 23, 2012

Using the FileSystemWatcher Class

The FileSystemWatcher class does exactly what the name implies - it watches the file system. Basically you just give it a path and it fires events when certain things happen to that path. The FileSystemWatcher can listen for rename, delete, change, and create. Let's hook it up and listen for renamed files.

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\MyDirectory";
watcher.Renamed += new RenamedEventHandler(watcher_Renamed)
watcher.EnableRaisingEvents = true;

Once you hook the events you want, in this case Renamed, you have to set EnableRaisingEvents to true to begin watching. In this example, the method watcher_Renamed will be called whenever any file in the folder C:\MyDirectory is renamed. The RenamedEventHandler contains lots of good information about the renamed file - like the old file name and the new file name.

void watcher_Renamed(object sender, RenamedEventArgs e)
{
  Console.WriteLine("File Renamed: Old Name: " + e.OldName +
    " New Name: " + e.Name);
}
All of the other events in the FileSystemWatcher class will pass a FileSystemEventArgs object to the event handler.

watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Created);

FileSystemEventArgs contain the filename, the full path, and what action caused the event.
So what if you want to watch a single file or a single type of file (like .txt files)? The FileSystemWatcher contains a Filter property that can be used to do that.

//watches only myFile.txt
watcher.Filter = "myFile.txt";
//watches all files with a .txt extension
watcher.Filter = "*.txt";

Like the second example in the above snippet shows, the Filter property can accept wildcards. In this case, events will only be fired when a file with a .txt extension changes.
The last important piece of the FileSystemWatcher is the property IncludeSubdirectories. The property tells the class to watch the folder you gave and all folders contained in it - and folders contained within those, etc.

No comments:

Post a Comment