Monitor the file system with FileSystemWatcher in C# .NET Part 4: other features
January 14, 2015 Leave a comment
In the first three parts of this mini-series – starting here – we looked at how to subscribe to the events raised by a FileSystemWatcher object. FileSystemWatcher has a couple more properties that can be interesting.
Consider the following code:
static void Main(string[] args) { RunVariousFeaturesExample(); Console.ReadKey(); } private static void RunVariousFeaturesExample() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\mydirectory"; watcher.Filter = "*.txt"; watcher.IncludeSubdirectories = true; watcher.NotifyFilter = NotifyFilters.Security | NotifyFilters.Size; watcher.Changed += watcher_Changed; watcher.EnableRaisingEvents = true; } static void watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("A change occurred in the monitored directory. Change type: {0}, file name: {1}", e.ChangeType, e.Name); }
We set the path to be monitored as usual. We can filter the file names to be monitored. Here we’re interested in text files only. We also specify that we want to monitor all subfolders of the “Path” directory through the IncludeSubdirectories property. With NotifyFilter we can further refine the cases when we want to be notified of a file change. Here we want to be notified if either the file size changes or the security properties have been updated. Then we subscribe to the generic Changed event which is raised in case an existing file changes.
In the below example I’ve updated the security settings of a file and it successfully raised the Changed event:
Read all posts dedicated to file I/O here.