I would like to make a backup when a filen is deleted - or actually prior to being deleted.
I tried using the FileSystemWatcher but it only raises an event when the file is already deleted, making it impossible to copy the file.
Heres the code I tried:
var watcher = new FileSystemWatcher(@"C:\folderToWatch");
//watcher.Changed += WatchEvent;
//watcher.Created += WatchEvent;
//watcher.Renamed += WatchEvent;
watcher.Deleted += WatchEvent;
watcher.EnableRaisingEvents = true;
With the WatchEvent method as follows:
private static void WatchEvent(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, Path.Combine(@"C:\folderToWatchBackup", e.Name));
Console.WriteLine($"{e.FullPath} was {e.ChangeType}");
}
Ofcourse it throws an exception when trying to copy the file that was already deleted.
I also tried listen on the Changed and Renamed events but they do not do the job either.
The perfect scenario would be an event like so:
watcher.BeforeDelete += WatchEvent;
I would like some suggestions on how to implement the wanted functionality or maybe some ideas that could point me in the direction of something useful.
While googling around all I found was to write something in C or C++ so maybe this really is an impossible task for C#?
(This is my first question so I hope it makes sense).