tags:

views:

3003

answers:

4

How do I get the list of open file handles by process id in C#?

I'm interested in digging down and getting the file names as well.

Looking for the programmatic equivalent of what process explorer does.

Most likely this will require interop.

Considering adding a bounty on this, the implementation is nasty complicated.

+4  A: 

You can P/INVOKE into the NtQuerySystemInformation function to query for all handles and then go from there. This discussion on the SystInternals forum has details.

See also this Google groups discussion.

Mark Cidade
Good stuff. Ill see if I can get the interop going
Sam Saffron
+4  A: 

Ouch this is going to be hard to do from managed code.

There is a sample on codeproject

Most of the stuff can be done in interop, but you need a driver to get the filename cause it lives in the kernel's address space. Process explorer embeds the driver in its resources. Getting this all hooked up from C# and supporting 64bit as well as 32, is going to be a major headache.

Sam Saffron
Who cares about the code, that thing is useful! Even nicer than Process Explorer, for what it does.
Brian
+4  A: 

You can also run the command line app, Handle, by Mark Rusinovich, and parse the output.

Mark Cidade
A: 

Handle is great program, and the link to codeproject is good, but it's not Windows 7/64-bit compatible.

@Brian The reason for the code is that handle.exe is NOT redistributable. Nor do they release their source.

It looks as if .Net will not easily do this since it appears that an embedded device drive is requried to access the information. This cannot be done in .net without an unmanged DLL. It's relatviely deep kernel code when compared to typical .net coding. I'm surprised that WMI does not expose this.

mkm