How is it possible to understand which process deletes a file on the hard drive
See the question and my original answer on StackOverflowIf you're ok with a C# solution, you can use the Microsoft.Diagnostics.Tracing.TraceEvent nuget packagage. It's a wrapper over ETW (Event Tracing for Windows) events.
What happens is the Windows kernel traces everything, and you can get those traces in real time. But it's sometimes difficult to correlate them.
In your case, you're looking after file delete events, but unfortunately, these events have no process information attached to it, so I've used another event. Here is some sample code:
using System;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Session;
namespace TraceDeletes
{
class Program
{
static void Main(string[] args)
{
if (TraceEventSession.IsElevated() != true)
{
Console.WriteLine("To turn on ETW events you need to be Administrator, please run from an Admin process.");
return;
}
// we're watching that particular file
string filePath = @"C:\temp\New Text Document.txt";
ulong fileKey = 0;
string processName = null;
using (var session = new TraceEventSession("whatever"))
{
// handle console CTRL+C gracefully
Console.CancelKeyPress += (sender, e) => session.Stop();
// we filter on events we need
session.EnableKernelProvider(
KernelTraceEventParser.Keywords.DiskFileIO |
KernelTraceEventParser.Keywords.FileIOInit);
// this event has no process information
session.Source.Kernel.FileIOFileDelete += data =>
{
if (data.FileKey == fileKey)
{
Console.WriteLine(data.FileName + " was deleted by " + processName);
fileKey = 0;
processName = null;
}
};
// this event has process information (id, name)
// it happens before delete, of course
// we remember the FileKey
session.Source.Kernel.FileIOQueryInfo += data =>
{
if (string.Compare(data.FileName, filePath, StringComparison.OrdinalIgnoreCase) == 0)
{
fileKey = data.FileKey;
processName = data.ProcessName;
}
};
// runs forever, press CTRL+C to stop
session.Source.Process();
}
}
}
}
If you create that "C:\temp\New Text Document.txt" file and delete it using Windows Explorer, you should see this:
C:\temp\New Text Document.txt was deleted by explorer
Note: ETW is of course usable using other languages, but it's much easier with this .NET library.