11.23. Watching the Filesystem for Specific Changes to One or More Files or Directories

Problem

You want to be notified when a file and/or directory is created, modified, or deleted. In addition, you might also need to be notified of any of these actions for a group of files and/or directories. This can aid in alerting your application as to when a file, such as a log file, grows to a certain size, after which it must be truncated.

Solution

To be notified when an action takes place in the filesystem, you need to employ the FileSystemWatcher class. The following method, TestWatcher, sets up a FileSystemWatcher object to watch the entire C:\ drive for any changes. The changes are limited to any file with the extension .txt. At the end of this method, the events are wired up for each one of the changes listed in the NotifyFilter property:

public void TestWatcher( ) { FileSystemWatcher fsw = new FileSystemWatcher( ); fsw.Path = @"c:\"; fsw.Filter = @"*.txt"; fsw.IncludeSubdirectories = true; fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Attributes | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size | NotifyFilters.CreationTime| NotifyFilters.DirectoryName; fsw.Changed += new FileSystemEventHandler(OnChanged); fsw.Created += new FileSystemEventHandler(OnCreated); fsw.Deleted += new FileSystemEventHandler(OnDeleted); fsw.Renamed += new RenamedEventHandler(OnRenamed); fsw.Error += new ErrorEventHandler(OnError); fsw.EnableRaisingEvents ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.