Free mag vol1 | Page 832

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION  Source Code You can find the BinaryWriterReader application under the Chapter 20 subdirectory. Watching Files Programmatically Now that you have a better handle on the use of various readers and writers, you’ll look at the role of the FileSystemWatcher class. This type can be quite helpful when you want to monitor (or “watch”) files on your system programmatically. Specifically, you can instruct the FileSystemWatcher type to monitor files for any of the actions specified by the System.IO.NotifyFilters enumeration (many of these members are self-explanatory, but you should still check the .NET Framework 4.5 SDK documentation for more details). public enum NotifyFilters { Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, Size } To begin working with the FileSystemWatcher type, you need to set the Path property to specify the name (and location) of the directory that contains the files you want to monitor, as well as the Filter property that defines the file extensions of the files you want to monitor. At this point, you may choose to handle the Changed, Created, and Deleted events, all of which work in conjunction with the FileSystemEventHandler delegate. This delegate can call any method matching the following pattern: // The FileSystemEventHandler delegate must point // to methods matching the following signature. void MyNotificationHandler(object source, FileSystemEventArgs e) You can also handle the Renamed event using the RenamedEventHandler delegate type, which can call methods that match the following signature: // The RenamedEventHandler delegate must point // to methods matching the following signature. void MyRenamedHandler(object source, RenamedEventArgs e) While you could use the traditional delegate/event syntax to handle each event, you can certainly make use of lambda expression syntax as well (the downloadable code for this project does make use of lambda syntax, if you are interested). Next, let’s look at the process of watching a file. Assume you have created a new directory on your C: drive named MyFolder that contains various *.txt files (named whatever you like). The following Console Application (named MyDirectoryWatcher) monitors the *.txt files in the MyFolder directory and prints out messages when files are created, deleted, modified, or renamed: static void Main(string[] args) { Console.WriteLine("***** The Amazing File Watcher App *****\n"); 778