Enumerating File Handles in C#

醉酒当歌 提交于 2019-12-01 17:26:37

Well, you know it is possible, SysInternals' Handle utility does it. NtQueryInformation isn't going to be phased out, it is an essential low-level interface between Win32 and the "real" operating system.

What is however never going to happen is that the NtQueryInformation arguments that allow iterating handles is going to be documented. Because it doesn't stop just there, some muppet is going to use it to call CloseHandle() on a file that s/he doesn't want to be locked. Which is a very good way to destroy your hard disk content.

The process that owned the handle doesn't know the handle is closed. It will just keep writing to it, probably completely ignoring the "it didn't work" return code from WriteFile(). Which is harmless until the program opens another handle, getting the same value back as the one that was closed earlier. Now it starts writing a mix of garbage (intended for the previous handle) and new data to the handle. Utterly destroying the content of whatever it is writing to. Spin up the backup tapes if that's something like a mission critical database.

evilpie

Here is an ready class for C# http://sourceforge.net/projects/processhacker/

Sheng Jiang 蒋晟

You can call sysinternal's Handle and parse the result, or write a file system driver (could be a multi-human-year effort and can't be done in C#)

I found a working example of listing file handles with names in C# here...

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/ac990847-6d04-4ae0-aafe-8355bbc3f769

Scroll down to the last thread and follow the link there. And be forewarned, once you download the code, the comments are in French. Just so happens I'm taking French, so I can make sense of most of it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!