A Tech Log

October 16, 2008

FileSystemWatcher – Why Does It Stop Working

Filed under: Development — adallow @ 4:12 am

Interesting post at (all content bleow taken from this link):

Taken from: http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c9113/

“An application I was working on that used the FileSystemWatcher class and was intended to run 24/7 would periodically stop working. After a little searching, I managed to narrow it down to network outages. You see, the watcher was looking at a network drive, and intermittently (as networks will) it was dropping out and then coming back again. I soon learnt that, when this happens, the FileSystemWatcher loses track of what it was supposed to do.

Easy to fix? Well, it’s not too hard. Check out the example below. You can even test this on your local machine by simply removing the directory that is being searched:”

using System;
using System.IO;

namespace ConsoleApplication1
class Class1
private static FileSystemWatcher watcher =
new FileSystemWatcher();

static void Main(string[] args)

// set up the FileSystemWatcher object
private static void WatchFile()
// ***** Change this as required
watcher.Path = @”\\myServer\c$\test\”;

// For this example, I only care about when new files are
// created
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = “*.txt”;

// Add event handlers: 1 for the event raised when a file
// is created, and 1 for when it detects an error.
watcher.Changed += new FileSystemEventHandler(NewFile);
watcher.Error += new ErrorEventHandler(WatcherError);

// Begin watching.
watcher.EnableRaisingEvents = true;

// Define the found event handler.
private static void NewFile(object source, FileSystemEventArgs e)
Console.WriteLine(“A file has been found!”);

// The error event handler
private static void WatcherError(object source, ErrorEventArgs e)
Exception watchException = e.GetException();
MessageBox.Show(“A FileSystemWatcher error has occurred: ”
+ watchException.Message);
// We need to create new version of the object because the
// old one is now corrupted
watcher = new FileSystemWatcher();
while (!watcher.EnableRaisingEvents)
// This will throw an error at the
// watcher.NotifyFilter line if it can’t get the path.
Console.WriteLine(“I’m Back!!”);
// Sleep for a bit; otherwise, it takes a bit of
// processor time


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: