开发者

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

开发者 https://www.devze.com 2022-12-30 03:32 出处:网络
How do I get the list of open file handles by process id in C#? I\'m interested in digging down and getting the fi开发者_JAVA技巧le names as well.

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

I'm interested in digging down and getting the fi开发者_JAVA技巧le 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.


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.


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


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


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


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消