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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With