0

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).

  • I don't know, but it may be too much to ask for a system-level solution in C#. Perhaps you could surface some UI with its own file browser - in which case you could easily tap into such events.. – ne1410s Nov 08 '19 at 09:07
  • Possible duplicate of [C# File change/create/delete event](https://stackoverflow.com/questions/25047522/c-sharp-file-change-create-delete-event) – Diado Nov 08 '19 at 09:07
  • 2
    The answer in the dupe marked above details writing a filter driver, which would achieve what you want. As said in that answer though, it's not for the faint-hearted. – Diado Nov 08 '19 at 09:08

2 Answers2

0

As far as I'm aware this is not possible as most events will trigger AFTER your file is already deleted. I think your best bet is to run an OnChanged event instead. While this is not an ideal solution it does allow you to have the latest metadata of the file from when it was last changed.

0

The Deleted event means that the event is raised after deletion.

Because there is no Deleting event, you can't do what you want to do, as I know.

Perhaps with some kernel WinAPI...