是否可以使用.NET跟踪文件操作?

是否有可能以某种方式调用文件操作(如打开或关闭),我可以在操作系统请求进行之前处理它,如果可能,可以通过.NET取消它? 如果.NET没有这样的能力,我该怎么做?

你要做的事情可以做。 例如,病毒扫描程序会一直这样做。 您可以使用Process Monitor轻松监视文件活动。 您也可以使用FileSystemWatcher类在C#中以编程方式执行此操作。 但是,试图阻止程序打开或试图阻止程序访问该文件无法在C#中完成。 您将需要使用C或C ++。 您需要创建文件系统筛选器驱动程序 。 构建它是一件复杂的事情,但它正是你所需要的。 引用MSDN:

A file system filter driver intercepts requests targeted at a file system or another file system filter driver. By intercepting the request before it reaches its intended target, the filter driver can extend or replace functionality provided by the original target of the request. Examples of file system filter drivers include anti-virus filters, backup agents, and encryption products.

如果需要,可以挂钩Windows API。 看看这种方式在.NET / C#中做到这一点:

EasyHook Windows API

Sysinternals提供了一个名为Process Monitor的免费工具,其中一个function是附加到任意Windows进程(包括.NET应用程序)和捕获系统调用,包括文件打开,关闭,读取等。

您可以在Process Monitor下载页面下载它。

编辑

当我重新阅读你的问题时,我发现你正在询问拦截并可能取消此类操作。 我相信FileSystemWatcher类是你最好的选择,虽然我不认为它可以单方面取消文件操作 – 你需要构建某种协作机制来通知调用者中止其操作。

我很确定你必须在这种操作上进入内核,我很确定这意味着你需要在C中编码。查看文件系统驱动程序 。

更新:此SO链接可能会有所帮助。

更新:添加了谷歌搜索Windows文件系统驱动程序

ALSO 什么是开始使用Windows文件系统驱动程序开发的好资源?