Search code examples
c#filesystemwatcher

How to capture watch folder deletion events


I have a file watch directory named FileWatch

 C:\Users\MyFolder\FileWatch\Test

The FileWatch folder is the watch directory. My application is receicing all events which occur below the FileWatch directory.

However if I delete the FileWatch folder itself, no file system event is generated.

Is there any way to capture if a user deletes the FileWatch directory itself?


Solution

  • According to description of FileSystemWatcher class, events are raised when changed/deleted/created/renamed file or directory in the directory being monitored.

    So, it should not be watching directory itself. It monitors only files and directories inside that directory.

    Options (as stated before) - watch to directory C:\Users\MyFolder\FileWatch instead.

    UPDATE: If you want to watch only for directory C:\Users\MyFolder\FileWatch\Test deletion:

    string path = @"C:\Users\MyFolder\FileWatch"; // watch for parent directory
    if (!Directory.Exists(path)) // verify it exists before start
        return;
    
    FileSystemWatcher watcher = new FileSystemWatcher(path);
    // set option to track directories only
    watcher.NotifyFilter = NotifyFilters.DirectoryName;
    
    watcher.Deleted += (o, e) =>
    {
        if (e.FullPath == @"C:\Users\MyFolder\FileWatch\Test")
        {
            // If you are here, your test directory was deleted
        }
    };
    
    watcher.EnableRaisingEvents = true;