简体   繁体   English

如何在C#中的64位OS中获取进程所有者名称

[英]How to get process owner name in 64 bit OS in C#

How do I determine the owner of a process in C#? 如何确定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. 这段代码可以正常工作,但只获取那些32位进程的所有者名称。 The method return "no owner" for 64 bits processes. 对于64位进程,该方法返回“无所有者”。 Please help me, how I can get the processes owner names for both 32 bit processes and 64 bit processes. 请帮助我,我如何获得32位进程和64位进程的进程所有者名称。

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. 当您的代码是32位但目标进程是64位时,它也可以工作,因此这里也没有问题。

Possible reasons why you could get "NO OWNER": 您可能会收到“没有所有者”的可能原因:

  • You are trying to get the owner for which you have no permission (eg 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 (eg "System", with PID 4, or "System Idle Process" with PID 0). 您试图获取伪进程的所有者(例如,PID为4的“系统”或PID为0的“系统空闲进程”)。

BTW, also services have owners (regarding @weismat comment). 顺便说一句,服务也有所有者(关于@weismat评论)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM