How do I get the list of open file handles by proc

2018-12-31 22:31发布

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.

标签: c# .net
7条回答
唯独是你
2楼-- · 2018-12-31 22:39

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

查看更多
大哥的爱人
3楼-- · 2018-12-31 22:54

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

查看更多
只若初见
4楼-- · 2018-12-31 22:55

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.

查看更多
皆成旧梦
5楼-- · 2018-12-31 23:00

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

查看更多
情到深处是孤独
6楼-- · 2018-12-31 23:01

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

查看更多
余生请多指教
7楼-- · 2018-12-31 23:02

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

查看更多
登录 后发表回答