Monitor the file system with FileSystemWatcher in C# .NET Part 1
January 7, 2015 1 Comment
In this mini-series we’ll look at how you can use the FileSystemWatcher object to monitor the Windows file system for various changes.
A FileSystemWatcher object enables you to be notified when some change occurs in the selected part of the file system. This can be any directory, such as “c:\” or any subdirectory under the C: drive. So if you’d like to make sure you know if a change occurs on e.g. “c:\myfolder” – especially if it’s editable by your colleagues – then FileSystemWatcher is a good candidate.
Consider the following Console application:
class Program { static void Main(string[] args) { RunFirstExample(); Console.ReadKey(); } private static void RunFirstExample() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\mydirectory"; watcher.Created += watcher_Created; watcher.Deleted += watcher_Deleted; watcher.EnableRaisingEvents = true; } static void watcher_Deleted(object sender, FileSystemEventArgs e) { Console.WriteLine("File deleted. Name: {0}", e.Name); } static void watcher_Created(object sender, FileSystemEventArgs e) { Console.WriteLine("File created. Name: {0}", e.Name); } }
In RunFirstExample we specify that we’re interested in monitoring the c:\mydirectory directory. Then we subscribe to the Created and Deleted events which represent the insertion of a new file and the deletion of an existing file in the directory. The FileSystemEventArgs has a couple of properties to show the event type, such as “Created” or “Deleted” in a WatcherChangeTypes enumeration, the file name and the file full path. We then start running the monitoring process by setting EnableRaisingEvents to true.
Note the call to Console.ReadKey(); in Main. The process won’t magically run in the background once Main is done. The FileSystemWatcher must sit within a continuous process, such as a Windows service.
Run the above code and insert a new file into the monitored directory. Then delete the file and watch the console output. Insertion example:
File deleted:
Read the next part here.
Read all posts dedicated to file I/O here.
Thank you.