如何在 C# 中枚举系统上所有打开的文件?
尝试用 C# 枚举 Windows 系统上所有打开的文件。我找不到本地方法来执行此操作,除了使用 NtQuerySystemInformation API 之外还有其他方法吗?
谢谢。
Trying to enumerate all open files on a Windows system in C#. I cannot find a native way to do it, is there any other way other than using the NtQuerySystemInformation API?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是故意不包含在记录的 API 中的。枚举打开的文件永远无法在多任务操作系统上可靠地工作,您无法“冻结”操作系统并在枚举文件时阻止其他进程打开和关闭文件。竞争条件是无法解决的。唯一有记录的方法是尝试打开没有共享的文件。
是的,NtQuerySystemInformation就是后门。由 SysInternals 的 Handle 实用程序使用。并且由他们维护,因为每个新版本的 Windows 都需要更新该实用程序。
Yes, this was quite intentionally not included in the documented API. Enumerating open files can never work reliably on a multi-tasking operating system, you cannot 'freeze' the operating system and prevent other processes from opening and closing files while you enumerate them. The race condition is unsolvable. The only documented way is to try to open a file with no sharing.
Yes, NtQuerySystemInformation is the back door. Used by SysInternals' Handle utility. And maintained by them since every new version of Windows requires an update to the utility.
您可能可以通过首先枚举系统上的所有句柄,然后获取每个文件句柄的文件名来完成此操作。
这是我的一个旧程序,它枚举句柄,找到某个进程的进程句柄并打印它们。您需要将其从进程句柄更改为文件句柄。
http://nopaste.info/eb9917d719.html 但它使用NtQuerySystemInformation。
这描述了如何从句柄获取文件名:
http://msdn.microsoft.com/en-us/库/aa366789(VS.85).aspx
You probably can do it by first enumerating all handles on the system, and then getting the filename for each handle that is a filehandle.
This is an old program of me that enumerates handles, find the ones that are a process-handle to a certain process and prints them. You'll need to change it from process-handles to file-handles.
http://nopaste.info/eb9917d719.html But it uses NtQuerySystemInformation.
This describes how to get the filename from a handle:
http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx