gpt4 book ai didi

file - 如何了解哪个进程删除了硬盘驱动器上的文件

转载 作者:行者123 更新时间:2023-12-04 12:45:05 24 4
gpt4 key购买 nike

我有以下问题。我开发了一个将设置保留在首选项文件中的应用程序。在某个时间点,这些文件之一将被删除。无法从我的应用程序中删除此文件。

如何理解在Windows下哪个进程删除了硬盘驱动器上的文件?

编辑:
该问题很少出现。我正在寻找一个可以作为服务或其他方式运行的程序,因此我可以为该应用程序做一个补丁,如果有人删除文件并写出完成的过程,则可以在运行时进行监视。

最佳答案

如果可以使用C#解决方案,则可以使用Microsoft.Diagnostics.Tracing.TraceEvent nuget packagage。它是ETW(Event Tracing for Window)事件的包装。

Windows内核会跟踪所有内容,您可以实时获取这些跟踪。但是有时很难将它们关联起来。

就您而言,您正在照顾文件删除事件,但是不幸的是,这些事件没有附加任何过程信息,因此我使用了另一个事件。这是一些示例代码:

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();
}
}
}
}

如果创建该“C:\temp\New Text Document.txt”文件并使用Windows资源管理器将其删除,则应看到以下内容:
C:\temp\New Text Document.txt was deleted by explorer

注意:ETW当然可以与其他语言一起使用,但是使用此.NET库要容易得多。

关于file - 如何了解哪个进程删除了硬盘驱动器上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51654329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com