Is there a way to detect deletion of a file before windows performs the deletion? I found FileSystemWatcher class but the event is raised only after the delete action is per
You need a filesystem filter driver. However I strongly suggest that if you don't know the answer you probably shouldn't be doing it.
http://msdn.microsoft.com/en-us/library/windows/hardware/gg462968.aspx
I think the simpliest way is to use a hook to get notified (and eventually to stop) the process. It can't be done in .NET so you have to DllImport
a lot of structures and few functions to P/Invoke.
Let's start your job with the NtSetFileInformation
(undocumented) function. It's the function called by anything else when a file need to be deleted (with the FileDispositionInformation
structure).
Now the problem is how to hook that function (good luck, it's not easy). A good choice can be to use Microsoft Detours. Take a look to this article for an example. Its problem is that it's not free. An alternative solution (with a reasonable price and with a .NET interface) is Deviare but I never tried even their free version so I don't know how much it's good. If someone else knows a good interception tool...
Or may try ICopyHook interface.
http://msdn.microsoft.com/en-us/library/windows/desktop/bb776049%28v=vs.85%29.aspx
In CopyCallback method use FO_DELETE in wFunc parameter, to specify delete operation.
Disadvantage: Only prevent deletion in Windows Shell.