views:

215

answers:

5

I would like to know whether it is possible to enumerate file handles in c#, maybe using Win32API. This is easily done for window and process handles, but it seems that it is not possible for file handles.

While some functionality is offered by NtQuerySystemInformation, this is being phased out and therefore it is not recommended to use such a method.

A: 

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#)

Sheng Jiang 蒋晟
+1  A: 

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.

Hans Passant
A: 

Here is an ready class for C# http://processhacker.sourceforge.net/hacking/index.php

evilpie
A: 

thank you all, this information has certainly helped me out achieve what I had in mind...

teff
A: 

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.

iamix