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

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


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.


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

Tags:

C#

.Net