Search code examples
c#filesystemwatcher

C#: What happens to the FileSystemWatcher after watched folder is deleted


I am using FileSystemWatchers for some of the code I am developing. I do have one question though, what happens to an FSW when the folder it is watching is deleted?

My usecase is this:

  1. User creates directory Foo

  2. My code then watches Foo using and FSW

  3. User deletes Foo

  4. Later on, user recreates the Foo directory.

In this case, what happens to the original FSW? Will it still watch the new directory, or will I have to create a new one?

Any help is greatly appreciated.


Solution

  • TL;DR: No, the FSW will not automatically watch "Foo" after its been recreated.


    The easiest way is to verify it is to test it out, so I did.

    If you use an instance of FileSystemWatcher to watch a directory "Foo", and then delete that directory that is being watched, then the FileSystemWatcher stops watching that directory.

    Even after recreating a directory with the same name "Foo", the FileSystemWatcher will no longer raise events for any changes in that directory.

    After "Foo" is deleted and recreated, trying to "reset" the FileSystemWatcher by setting its Path property to "Foo" and EnableRaisingEvents property to true does not work consistently - it works correctly the first time around, but fails to do so if "Foo" is deleted and recreated a second time around. (This was tested in Visual Studio 2017 Community Edition).

    Sadly, it appears that in such a case, the only consistent way of making the FileSystemWatcher work as expected is to create a new instance of the FileSystemWatcher.