FileSystemWatcher�Why Does It Stop Working?

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();

      [STAThread]
      static void Main(string[] args)
      {
         WatchFile();
         Console.ReadLine();
      }

      // 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!");
         File.Delete(e.FullPath);
      }

      // 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)
         {
            try
            {
               // This will throw an error at the
               // watcher.NotifyFilter line if it can't get the path.
               WatchFile();
               Console.WriteLine("I'm Back!!");
            }
            catch
            {
               // Sleep for a bit; otherwise, it takes a bit of
               // processor time
               System.Threading.Thread.Sleep(5000);
            }
         }
      }
   }
}


Comments

  • watcher destruction (really VB.Net question)

    Posted by wd60152 on 02/16/2005 02:31pm

    I noticed that new "watcher"s are allocated in the error handler until the net connection is back up. What is happening behind the scenes to keep from leaking the old "watcher"s?

    • Re: Watcher destruction

      Posted by Zeb on 02/16/2005 04:38pm

      As far as I know, the .Net Garbage collecter should see that they are no longer referenced and clean them up itself. This goes for C# or Vb.Net. As to them being created until the net connection is back, another strange thing I noticed in testing is that the error doesn't get thrown until the connection comes back. I can't explain why, but when I was testing I removed the network cable from the back of my computer, waited - nothing. Then, when I plug it back in I get the error message and then the working again message. So this means that for network outages, it doesn't sit there creating new FSW until the connection is back (although, unfortunately this isn't by design, more by luck - but again, it wouldn't be hard to do your own checks, like pinging the server instead of trying to create FSW until you get success, and this could be a better way to do it). If you test it locally by removing a folder though, the error comes up immediately. I can guess why the error is getting thrown at different times, but I don't know for sure so it's probably best I don't post my thoughts and send ppl down the wrong track.

      • Re: Watcher destruction

        Posted by Brian on 04/20/2012 12:26am

        FilSystemWatcher inherets a class that impliments IDisposable, so good practice (albeit the finalizer of the base Component class makes the call) would be to make an explicit call watcher.Dispose()

        Reply
      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds