
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
734
|
Chapter 12: Filesystem I/O
and/or directories. This can aid in alerting your application 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 TestWatcher method shown in Example 12-12 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.
Example 12-12. Using the FileSystemWatcher class
public static void TestWatcher( )
{
using (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); ...