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);}

category: .NET, C#    

8 Comments so far

  1.    Jim on January 16th, 2007

    What’s the VB.NET equivalent of this?



  2.    ... on February 28th, 2007

    Very nice site! Good work.

  3.    ... on March 11th, 2007

    Nice site you have!

  4.    ... on March 14th, 2007

    Du musst ein Fachmann sein – wirklich guter Aufstellungsort, den du hast!

  5.    ... on March 16th, 2007

    pagine piuttosto informative, piacevoli =)

  6.    ... on March 18th, 2007

    luogo grande:) nessun osservazioni!

  7.    ... on March 19th, 2007

    Great site! Good luck to it’s owner!

  8.    Andrew on March 25th, 2007

    Much appericated, thank you! Saved me a lot of time, which i’m very short on.