4

How can I find the owner of a given process in C#? The class System.Diagnostics.Process doesn't seem to have any properties or methods that will get me this information. I figure it must be available because it is shown in the Windows Task Manager under the "User Name" column.

My specific scenario involves finding the instance of a process (such as taskhost.exe) which is running as "Local Service". I know how to find all the instances of taskhost using

Process.GetProcessesByName("taskhost")

So now I just need to know how to identify the one which is running as local service.

Luke Foust
  • 2,234
  • 5
  • 29
  • 36

3 Answers3

8

Use WMI to retrieve instances of the Win32_Process class, then call the GetOwner method on each instance to get the domain name and user name of the user under which the process is running. After adding a reference to the System.Management assembly, the following code should get you started:

// The call to InvokeMethod below will fail if the Handle property is not retrieved
string[] propertiesToSelect = new[] { "Handle", "ProcessId" };
SelectQuery processQuery = new SelectQuery("Win32_Process", "Name = 'taskhost.exe'", propertiesToSelect);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(processQuery))
using (ManagementObjectCollection processes = searcher.Get())
    foreach (ManagementObject process in processes)
    {
        object[] outParameters = new object[2];
        uint result = (uint) process.InvokeMethod("GetOwner", outParameters);

        if (result == 0)
        {
            string user = (string) outParameters[0];
            string domain = (string) outParameters[1];
            uint processId = (uint) process["ProcessId"];

            // Use process data...
        }
        else
        {
            // Handle GetOwner() failure...
        }
    }
Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
1

You can use the Handle property on the process and pass it to GetSecurityInfo through the P/Invoke layer to get the security information on the process.

It's the same as this question:

How do I get the SID / session of an arbitrary process?

Community
  • 1
  • 1
casperOne
  • 73,706
  • 19
  • 184
  • 253
0

Might want to try the code at this link

First result in google search for "C# get process owner"

Most likely the task manager uses the Win32 API via C to do this. That process is also outlined in the link above.

Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177