-1

How do I determine the owner of a process in C#?

public string GetProcessOwner(int processId)
{
    string query = "Select * From Win32_Process Where ProcessID = " + processId;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get();

    foreach (ManagementObject obj in processList)
    {
        string[] argList = new string[] { string.Empty, string.Empty };
        int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
        if (returnVal == 0)
        {
            // return DOMAIN\user
            return argList[1] + "\\" + argList[0];
        }
    }

    return "NO OWNER";
}

I detailed studied and implemented the code as given above. This code works fine but only gets the owner names of those processes which are 32 bits. The method return "no owner" for 64 bits processes. Please help me, how I can get the processes owner names for both 32 bit processes and 64 bit processes.

Community
  • 1
  • 1

1 Answers1

3

No, that code works "fine". It also works when your code is 32bit but the target process is 64bit, so no issue here as well.

Possible reasons why you could get "NO OWNER":

  • You are trying to get the owner for which you have no permission (e.g. you are running as non-privileged user, but trying to get the owner of a privileged one).
  • You are trying to get the owner of a pseudo process (e.g. "System", with PID 4, or "System Idle Process" with PID 0).

BTW, also services have owners (regarding @weismat comment).

Christian.K
  • 47,778
  • 10
  • 99
  • 143