Getting Windows Process Owner Name

The System.Diagnostics.Process class gives almost every data about a running process. But, the most-wanted information it doesn’t give about a process is the process owner name. And I ran across a situation recently that asked for the same thing – here is the code I used. However, this method will not work for certain processes because the current user will most likely not have permissions to query about those processes (but it was sufficient for my needs).

[DllImport ("advapi32.dll", SetLastError = true)]
static extern bool OpenProcessToken (IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

[DllImport ("kernel32.dll", SetLastError = true)]
[return: MarshalAs (UnmanagedType.Bool)]
static extern bool CloseHandle (IntPtr hObject); 

static uint TOKEN_QUERY = 0x0008;

foreach (Process p in Process.GetProcesses ())
  ph = IntPtr.Zero;
    OpenProcessToken (p.Handle, TOKEN_QUERY, out ph);
    WindowsIdentity wi = new WindowsIdentity(ph);
    Console.WriteLine (p.ProcessName + " owned by " + wi.Name);
  catch (Exception xcp)
    Console.WriteLine (p.ProcessName + ": " + xcp.Message);
    if (ph != IntPtr.Zero) {CloseHandle (ph);}

8 thoughts on “Getting Windows Process Owner Name”

Comments are closed.