9.19 Monitor the File System for Changes


Problem

You need to react when a file system change is detected in a specific path (such as a file modification or creation).

Solution

Use the System.IO.FileSystemWatcher component, specify the path or file you want to monitor, and handle the Created , Deleted , Renamed , and Changed events.

Discussion

When linking together multiple applications and business processes, it's often necessary to create a program that waits idly and becomes active only when a new file is received or changed. You can create this type of program by scanning a directory periodically, but you face a key tradeoff . The more often you scan, the more system resources you waste. The less often you scan, the longer it will take to detect a change. The solution is to use the FileSystemWatcher class to react directly to Windows file events.

To use FileSystemWatcher , you must create an instance and set the following properties:

  • Path indicates the directory you want to monitor.

  • Filter indicates the types of files you are monitoring.

  • NotifyFilter indicates the type of changes you are monitoring.

The FileSystemWatcher raises four key events: Created , Deleted , Renamed , and Changed . All of these events provide information through their FileSystemEventArgs parameter, including the name of the file ( Name ), the full path ( FullPath ), and the type of change ( ChangeType ). The Renamed event provides a RenamedEventArgs instance that derives from FileSystemEventArgs , and it adds information about the original file name ( OldName and OldFullPath ). If you need to, you can disable these events by setting the FileSystemWatcher.EnableRaisingEvents property to false . The Created , Deleted , and Renamed events are easy to handle. However, if you want to use the Changed event, you need to use the NotifyFilter property to indicate the types of changes you are looking for. Otherwise, your program might be swamped by an unceasing series of events as files are modified.

The NotifyFilter property can be set using any combination of the following values from the System.IO.NotifyFilters enumeration:

  • Attributes

  • CreationTime

  • DirectoryName

  • FileName

  • LastAccess

  • LastWrite

  • Security

  • Size

The following example shows a Console application that handles Created and Deleted events and tests these events by creating a test file.

 using System; using System.IO; using System.Windows.Forms; public class FileWatcherTest {     private static void Main() {         // Configure the FileSystemWatcher.         FileSystemWatcher watch = new FileSystemWatcher();         watch.Path = Application.StartupPath;         watch.Filter = "*.*";         watch.IncludeSubdirectories = true;         // Attach the event handler.         watch.Created += new FileSystemEventHandler(OnCreatedOrDeleted);         watch.Deleted += new FileSystemEventHandler(OnCreatedOrDeleted);         watch.EnableRaisingEvents = true;         Console.WriteLine("Press Enter to create a file.");         Console.ReadLine();         if (File.Exists("test.bin")) {             File.Delete("test.bin");         }         FileStream fs = new FileStream("test.bin", FileMode.Create);         fs.Close();         Console.WriteLine("Press Enter to terminate the application.");         Console.WriteLine();         Console.ReadLine();     }     // Fires when a new file is created in the directory being monitored.     private static void OnCreatedOrDeleted(object sender,        FileSystemEventArgs e) {         // Display the notification information.         Console.WriteLine("\tNOTIFICATION: " + e.FullPath +           "' was " + e.ChangeType.ToString());           Console.WriteLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net