Search code examples
eventsc#-4.0filesystemwatcher

Unwiring events not working with FileSystemWatcher


I have an application that is using FileSystemWatcher to monitor a folder for changes to files. The problem is that when it catches these events, it needs to do changes to those documents (updating links), and this of course triggers the events again, throwing the application into a loop.

So I tried this:

    UnWireEvents(); //Turn off the events while updating the documents
            ChangeAllLinks();
            WireEvents(); //Turn the events back on 

   private void WireEvents()
            {
                _monitor.FileChanged += new EventHandler(_monitor_FileChanged);
            }

            private void UnWireEvents()
            {
                _monitor.FileChanged -= new EventHandler(_monitor_FileChanged);
            }

But it doesn't seem to work, the application still goes into a loop. So why doesn't it work, and what do I need to do instead?


Solution

  • Instead of unhooking your event handler you could set the EnableRaisingEvents property of the FileSystemWatcher class to false disabling all Create/Rename/Delete/Change events. After you have changed your links simply enable the FileSystemWatcher by setting EnableRaisingEvents to true.