Search code examples
c#eventsfilesystemwatcher

FileSystemWatcher with filter doesn't watch deleted maps


I've created a filesystemwatcher to watch a certain directory and watch at files with the Tests extension.

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = somepath;
watcher.Filter = "*.Tests";
// Hooked changed, deleted and created events
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;

The events trigger correctly when a file with the Tests extension is created, removed or changed in the watched directory or in it's subdirectories.

The problem is if I for example remove a map in the watched directory that has files with the Tests extension in it. No event is triggered then, allthough many files with the Tests extension are removed.

Is there a way I can make this happen?


Solution

  • Well, the problem is that the files aren't actually deleted when the folder is - so the FileSystemWatcher has no way of filtering those. You only get one delete - for the directory. If you do need to handle this in practice, you'll have to use a separate FileSystemWatcher to watch for deleting whole directories.

    Of course, this also depends on how the delete is done - a lot of applications still do the "delete all the files, then the directory". You can usually tell the difference very easily - if it takes time to delete a directory with lots of files, it's deleting the files first. Those will work correctly for your case - but others will fail.

    If you just need a work-around, most applications will switch to a per-file delete when it's impossible to delete the directory with a single delete - for example, when there's locked files in the directory.