How To: BlockingRestricting certain file types from being saved to a directory using FileSystemWatcher

February 25, 2009

A user a posted a question on the forum section asking if there’s a way to restrict files from being saved in a directory. I know you can do this via the FileSystemWatcher class so I quickly whipped my Visual Studio 2008 IDE and started building a prototype application to demonstrate the solution.

The first thing that you need to do is to set-up some key details on what we want to watch/monitor

Next, the FileSystemWatcher specify what directory you want to monitor.

After that you need to setup the notification filters on what type of filesystem changes you want to watch;

And finally, we need to set-up the FileSystem events you want our FileSystem. In this case, we only want to monitor Created and Renamed events.

Now, let’s start coding our event handlers.

For our event handler, I decided to use one method that would handle both the Created and Rename event. Ideally you want to seperate this to into two different methods because you might want to handle the tow events differently but since all I want to do is to block filesfolders that doesn’t match my criteria i decided to handle them both using a single method called FileSystemHandler.

Below is the implementation detail for our FileSystemHandler method.

What the function above is doing is that it checks to see if the filesystem object that was created on the directory is either a file or a directory. If it is a directory, automatically delete it since we dont want any directory to be saved on our folder. If it is a file we need to check if it’s extension matches the allowed file extension. If it matches the allowed extension we let it thru. If it doesn’t we call the the Delete method on the FileInfo object to delete the file.

All we need to do now is to tell the watcher to start monitor our folder

Setting EnableRaisingEvents to true triggers our watcher to start monitoring the folder. Setting it to false will stop the watcher.

And we are done! Now we have an application that blocks saving or renaming of files in a folder that doesn’t match the allowed file extension.

Below is the full listing of the code for the demo project I built for this article:

As always, you can download the code for the complete project here: (40.38 KB)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.