.NET Tip: Receive Notification When a File is Updated

Using the FileSystemWatcher class provides you with a very simple but flexible way to monitor the file system. It can be used to monitor directories, individual files, or groups of files. It also can be configured only to notify your application of certain types of changes. For this example, I'll show you a class that watches for changes in the LastWrite property of a specific file. I use this class to watch for changes in text files that contain the body of an email message that is sent when the status of your system changes. When one of these text files changes, the application can detect the change and cache the new contents of the file. Here is what the class looks like:

The constructor for my MessageFileWatcher class takes the path to the directory where the file is stored as well as the specific file name as parameters. A new FileSystemWatcher variable is created and the Path and Filter properties are set to the parameters passed into the constructor. Next, the NotifyFilter property is set to indicate the type of change which is of interest. In this case, I want to be notified every time the file is written, so I am using LastWrite. I then hook one of my methods into the Changed event of the FileSystem Watcher and enable it to raise events. I've included the OnChanged event handler for completeness, but the code in this method will depend upon your application. That is all there is to it. Here is an example usage of the MessageFileWatcher class:

This provides a simple way to monitor the files used by your application. You may want to further explore the Filter and NotifyFilter properties as well as the various events available to make best use of the FileSystemWatcher class.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

Comments

There are no comments yet. Be the first to comment!

You must have javascript enabled in order to post comments.

Leave a Comment

Your email address will not be published. All fields are required.

Name

Email

Title

Comment

Top White Papers and Webcasts

The 2014 State of DevOps Report — based on a survey of 9,200+ people in IT operations, software development and technology management roles in 110 countries — reveals:
Companies with high-performing IT organizations are twice as likely to exceed their profitability, market share and productivity goals.
IT performance improves with DevOps maturity, and strongly correlates with well-known DevOps practices.
Job satisfaction is the No. 1 predictor of performance against organizational …