Sam Saffron
Sam Saffron

Reputation: 131112

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

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.

Upvotes: 45

Views: 66037

Answers (7)

Sam Saffron
Sam Saffron

Reputation: 131112

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.

Upvotes: 26

manuc66
manuc66

Reputation: 2829

Have a look at this file : http://vmccontroller.codeplex.com/SourceControl/changeset/view/47386#195318

And use:

DetectOpenFiles.GetOpenFilesEnumerator(processID);

Demo:

using System;
using System.Diagnostics;

namespace OpenFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var openFiles = VmcController.Services.DetectOpenFiles.GetOpenFilesEnumerator(Process.GetCurrentProcess().Id))
            {
                while (openFiles.MoveNext())
                {
                    Console.WriteLine(openFiles.Current);
                }
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

It has dependency over assembly System.EnterpriseServices

Upvotes: 12

mkm
mkm

Reputation: 29

Handle is great program, and the link to codeproject is good.

@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.

Upvotes: 2

user541686
user541686

Reputation: 210352

Take a look at wj32's Process Hacker version 1, which can do what you asked, and more.

Upvotes: 3

Kiquenet
Kiquenet

Reputation: 14976

Perhaps using command line tool:

OpenedFilesView v1.50 - View opened/locked files in your system (sharing violation issues)

http://www.nirsoft.net/utils/opened_files_view.html

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 99957

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

Upvotes: 11

Mark Cidade
Mark Cidade

Reputation: 99957

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

Upvotes: 12

Related Questions