Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileSystemWatcher does not notify on deleting the path directory itself

I am using a FileSystemWatcher in my code to track any change/rename/addition of file under the monitored directory. Now I need a notification if the monitored directory itself gets deleted.

Any suggestions on how to achieve this?

I was attempting to add a second watcher on the parent directory ( C:\temp\subfolder1 in the sample below) and filter the events to the fullpath of the monitored directory ( C:\temp\subfolder1\subfolder2).

But this won't work if the deletion is done a directory level higher and I do not want to monitor the whole file system. In the sample below it should fire on deleting C:\temp as well, not only on deleting C:\temp\subfolder1.

  class Program
  {
    static void Main(string[] args)
    {
      FileSystemWatcher watcher = new FileSystemWatcher();
      watcher.Path = @"C:\temp\subfolder1\subfolder2";
      watcher.EnableRaisingEvents = true;

      watcher.Changed += OnChanged;
      watcher.Created += OnChanged;
      watcher.Deleted += OnChanged;
      watcher.Renamed += OnChanged;

      Console.ReadLine();
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
      Console.WriteLine(e.FullPath);
    }
  }
like image 365
clemensoe Avatar asked Mar 03 '23 23:03

clemensoe


1 Answers

You can subscribe to the FileSystemWatcher.Error Event. This will fire when the parent directory gets deleted. Then you can make the appropriate checks to see if this was caused by the folder deletion.

like image 199
crankedrelic Avatar answered Apr 07 '23 20:04

crankedrelic