How to Get the List of Open File Handles by Process in C#

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

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.

Getting the file handles of given process

An easy solution would be to use handle.exe and read its output. Another solution is to use P/Invoke with NtQuerySystemInformation function. This and this forum post on SysInternals has more details as well as this article on CodeProject. Doing it in managed code could be very difficult as you will need to write a driver to read the kernel address space.

I would suggest you to expose the needed functionality in a Win32 function that you could call from managed code.

C# List currently open files and programs

You can get a list of running processes with their information

public static string ListAllProcesses()
{
StringBuilder sb = new StringBuilder();

// list out all processes and write them into a stringbuilder
ManagementClass MgmtClass = new ManagementClass("Win32_Process");

foreach (ManagementObject mo in MgmtClass.GetInstances())
{
sb.Append("Name:\t" + mo["Name"] + Environment.NewLine);
sb.Append("ID:\t" + mo["ProcessId"] + Environment.NewLine);
sb.Append(Environment.NewLine);
}
return sb.ToString();
}

The only method (That I know) to see if the process is opened by user or system is to check it's owner. If it's system, then it's not run by user:

//You will need to reference System.Management.Dll and use System.Management namespace
public string GetProcessOwner(string processName)
{
string query = "Select * from Win32_Process Where Name = \"" + processName + "\"";

ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();

foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
string owner = argList[1] + "\\" + argList[0];
return owner;
}
}

return "NO OWNER";
}

For the list of opened files, It is possible to do using Managed Code which is somehow hard. Here is an example on codeproject demonstrating the same matter



Related Topics



Leave a reply



Submit