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

后端 未结 7 1363
春和景丽
春和景丽 2020-11-22 13:01

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 program

相关标签:
7条回答
  • 2020-11-22 13:42

    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.

    0 讨论(0)
  • 2020-11-22 13:43

    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.

    0 讨论(0)
  • 2020-11-22 13:45

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

    0 讨论(0)
  • 2020-11-22 13:53

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

    0 讨论(0)
  • 2020-11-22 13:57

    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

    0 讨论(0)
  • 2020-11-22 14:01

    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

    0 讨论(0)
提交回复
热议问题