How to get the user name or owner of a process in .net

20,212

Solution 1

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...
        }
    }

Solution 2

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?

Share:
20,212
Luke Foust
Author by

Luke Foust

Although I currently work mainly on the Microsoft .net stack, I have experience with Java, Perl, PHP and many others in the past.

Updated on January 26, 2020

Comments

  • Luke Foust
    Luke Foust over 4 years

    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.