4
votes

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);
    }
  }
2
The scope of notifications will only be up to the folder path that you specify in the watcher - why would it work for any folders higher up ? - auburg
Well, it can't be deleted. Your program has a handle opened on the directory object. Consider that what actually happened is that the directory got moved to the recycle bin. - Hans Passant

2 Answers

6
votes

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.

1
votes

@crankedrelic Thanks for contributing! In order to get both deletion cases (permanently and move to recycle bin) I have to use this code:

private static void OnError(object sender, ErrorEventArgs e)
{
  Exception ex = e.GetException();
  if (ex is Win32Exception && (((Win32Exception)ex).NativeErrorCode == 5))
  {
    Console.WriteLine($"Directory deleted permanently: { watcher.Path }");
  }
}

private static void OnChanged(object sender, FileSystemEventArgs e)
{
  if (!Directory.Exists(watcher.Path))
  {
    Console.WriteLine($"Directory deleted (recycle bin): { watcher.Path }");
  }
}