Search code examples
c#.net.net-2.0filesystemwatcher

FileSystemWatcher and network disconnect?


How can I make it work in a network? It works then it stops working without reason (maybe because the network isn't perfect).


Solution

  • You need to reconnect with FileSystemWatcher.

    Make your variable of type FileSystemWatcher global to your class, add the event WatcherError.

    Inside the method, add something like that :

      private static void WatcherError(object source, ErrorEventArgs e)
      {
         watcher = new FileSystemWatcher();//You might want to do a method and to setup all config...
         while (!watcher.EnableRaisingEvents)
         {
            try
            {
               watcher = new FileSystemWatcher();//You might want to do a method and to setup all config...
            }
            catch
            {
               System.Threading.Thread.Sleep(30000); //Wait for retry 30 sec.
            }
         }
      }
    

    You do not want to use watcher = new... you would prefer to have a method that will add all event and setup the path but the code above give you a good idea of what to do.