.NET FileSystemWatcher

This week, I had to put together a simple application which watched a specific directory for the creation of a file with a given name. The goal was to process the contents of the file and then delete the file. The directory should be continually monitored and each subsequent file creation should be processed.


Since we do most of our development in C#, it was a simple task to identify the FileSystemWatcher object as the class I wanted to use.

The FileSystemWatcher is simple to use and configure, but I found I had to write a little bit of defensive code to get it working properly. To configure the FileSystemWatcher , you instance the class, add the name of the directory you want to monitor. You also need to add event handlers to handle the events which you want your code to deal with. You can add filters to only trigger events for specific filename patterns as well.

The events you can watch for include creation, deletion, rename, and change events.

To handle an event, simply assign a delegate-type function to the list of event handlers on the object (the following assigns the function FileCreated to the FileSystemWatcher fsWatcher object and watched for Create events:

    fsWatcher.Created += new FileSystemEventHandler(FileCreated);

All simple enough. The issue I ran into was caused by a race condition where another process was creating a file I was watching for would start writing to the file and the File Create event would get triggered before the file write was completed by the other process and consequently when my process tried to access the file, it was locked.

I got around this by using the FileChanged event and checking whether the file “existed” in a form I could process by calling FileInfo.Exists. If the file was locked by another process, another FileChanged event would be fired when the file was unlocked and ready for me to process.

Let me know if you want to see example code.

2 thoughts on “.NET FileSystemWatcher

  1. re: .NET FileSystemWatcher, January 29, 2010 — Martin Waldron

    Hi, thanks for the article. I would love to see your .NET FileSystemWatcher example. Thanks, Rick

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s