Tags

, , , , , , ,

Have you ever needed to monitor a specific directory or file for changes? .Net Framework has a class called FileSystemWatcher within System.IO namespace that allows developers to take action when a specific event occurs in the File System. In this posting, I’ll show you how you can use the FileSystemWatcher class to monitor your files or directories.

For our sample, let’s use the following hypothetical scenario: your company hosts its own website and for months, without success, you have been asking content editors not to store their image files within the folder reserved for web pages only. So, you decide to monitor the folder and take action if any violation happens.

How do you get this done using FileSystemWatcher? In the code sample below, you will notice that you just need to create an instance of FileSystemWatcher, add event handlers for the events you want to monitor, and tell your object to watch for events. It’s that simple!

FileSystemWatcher Class Implementation

In the implementation of the Created event handler above, I am just checking for extensions of image files explicitly. The FileSystemWatcher has a property called “Filter”, which allows you to define a mask of the type of files to watch (“*.jpg”, “doc*.*”, etc), but I couldn’t get more than one file extension associated with this property (if you know of another way, let me know).

So, still in the implementation sample, if an image file is created or copied into the monitored folder, an e-mail is fired to alert of the violation and the file is automatically deleted from the folder. Also, just to play nice and prevent any problems if the only copy of the file is deleted, the e-mail will also have a copy of the file attached to it. Another option would be to automatically move the file to the correct directory instead of just deleting it; however, if you take that approach, you’ll also have to check for crashes on the filename, at minimum.

Besides the Created event illustrated in our sample, you can also monitor the File System for the following events: Changed, Deleted, and Renamed. In our sample, we could also have implemented the Renamed event handler to prevent a user from bypassing the monitoring system by copying an image into the folder without an extension and renaming it later. And finally, if you are also looking for events in subdirectories, you can just set the FileSystemWatcher.IncludeSubdirectories property to true.

One thing to keep in mind is that, I have used a Console Application just to illustrate the implementation of the FileSystemWatcher class. However, if you decide to implement something similar that should run constantly, instead of a Console Application, you’ll probably want to look into creating a Windows Service and get your monitoring application running in the background.

Have Fun!

Advertisements