C# query for process owner (Windows 7 x64)

4.5k views Asked by At

I would like to know how to query for a process's owner in (or via) C#. I've tried the example at http://www.codeproject.com/KB/cs/processownersid.aspx.

WMI: Can query all process and their owners, but it's far too slow.

WIN32: Fast, but I get a permission denied exception when querying for owner of any process but my own.

I've tried to implement impersonation to solve the WIN32 issue, no go. I've also tried running the compiled .exe as an administrator, no go. I'm only a few months into this C# thing, so go easy.

2

There are 2 answers

5
arx On BEST ANSWER

I added the following to the Win32 example from: http://www.codeproject.com/KB/cs/processownersid.aspx

static void ProcessSID(Process process)
{
    string sid;
    ExGetProcessInfoByPID(process.Id, out sid);
    Console.WriteLine("{0} {1} {2}", process.Id, process.ProcessName, sid);
}

static void Main(string[] args)
{
    foreach (Process process in Process.GetProcesses())
    {
        ProcessSID(process);
    }
}

and when I run it as administrator it successfully prints the SIDs for all processes (except System and protected processes such as audiodg). It doesn't produce an access-denied error.

Does this code work for you?

I'm also using Windows 7 x64.

Update

This works for all processes except RunAs processes. The problem is the internals of Process.Handle, which ask for too many permissions.

If you replace the call to Process.Handle with

IntPtr procHandle=OpenProcess(ProcessAccessFlags.QueryInformation, false, PID);

and add the following definitions then the code also works with RunAs processes.

[Flags]
enum ProcessAccessFlags : uint
{
    All = 0x001F0FFF,
    Terminate = 0x00000001,
    CreateThread = 0x00000002,
    VMOperation = 0x00000008,
    VMRead = 0x00000010,
    VMWrite = 0x00000020,
    DupHandle = 0x00000040,
    SetInformation = 0x00000200,
    QueryInformation = 0x00000400,
    Synchronize = 0x00100000,
    ReadControl = 0x00020000
}

[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
2
Oleg Kolosov On

Seems like I've misunderstood the question first, sorry. Just found an interesting topic on the subject which may help you.