Tuesday, September 15, 2009

File Monitoring in .NET

File monitoring applications can be easily developed in .NET using the FileSystemWatcher class. This class listens to changes in files system and raises events whenever changes happen. This article explains how to monitor changes in files and subdirectories of a directory using the FileSystemWatcher class.
The FileSystemWatcher is available within the System.IO namespace. We need to include the System.IO namespace for accessing the FileSystemWatcher class. In order to specify the folder to monitor we have to set the Path property of the FileSystemWatcher as shown below:

FileSystemWatcher fsw = new FileSystemWatcher();
fsw.Path = "c:\\fileWatcher";
If you want to monitor changes to a specific file then the Filter property should be used along with the Path property. The Filter property should be set to file name and the Path property should be set to the path of the folder as shown below
fsw.Path = "c:\\fileWatcher ";
fsw.Filter = "TestWatchFile.txt";
Wild card characters can also be used to specify set of files as shown below
fsw.Filter = "*.txt";
The FileSystemWatcher to begin monitoring we have to set the EnableRaisingEvents property to true
fsw.EnableRaisingEvents = true;

As mentioned before the FileSystemWatcher raises events whenever changes like creation, deletion etc happens to the specific folder or file. The events that are raised by FileSystemWatcher are Changed, Created, Deleted, Error and Renamed.

We need to write appropriate event handlers to handle these events. The FileSystemEventHandler has an argument named FileSystemEventArgs, which provides useful event data. The data provided by the FileSystemEventArgs are ChangeType which gives the type of change that occurred and Path which gives the full path of the affected file or folder.

A sample Changed event handler is given below
fsw.Changed += new FileSystemEventHandler(fsw_changed);
fsw.Deleted += new FileSystemEventHandler(fsw_changed);
fsw.Created += new FileSystemEventHandler(fsw_changed);
private void fsw_changed(object Sender,FileSystemEventArgs e)
{
MessageBox.Show("The file" + e.FullPath+ " was " + e.ChangeType.ToString() + " on " + System.DateTime.Now.ToString());
}

FileSystemObject class can be used to monitor files or folders by setting appropriate properties and handling the events raised by the class.

No comments:

Post a Comment