Blue Blip

Thoughts Technologies Ramblings Learning & Sharing

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;
  try
  {
    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);
  }
  finally
  {
    if (ph != IntPtr.Zero) {CloseHandle (ph);}
  }
}
Posted: Oct 02 2006, 11:24 PM by Siva M | with 8 comment(s)
Filed under: ,

Comments

Jim said:

What's the VB.NET equivalent of this?

Thanks,

Jim

# January 16, 2007 3:23 PM

... said:

Very nice site! Good work.

# February 28, 2007 2:38 AM

... said:

Nice site you have!

# March 11, 2007 11:46 PM

... said:

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

# March 14, 2007 3:15 PM

... said:

pagine piuttosto informative, piacevoli =)

# March 16, 2007 2:55 PM

... said:

luogo grande:) nessun osservazioni!

# March 18, 2007 6:20 AM

... said:

Great site! Good luck to it's owner!

# March 19, 2007 9:20 PM

Andrew said:

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

# March 25, 2007 12:23 AM