一尘不染

如何确定C#中进程的所有者?

c#

我正在寻找名称为“ MyApp.exe”的进程,并且我想确保获得了特定用户所拥有的进程。

我使用以下代码来获取进程列表:

Process[] processes = Process.GetProcessesByName("MyApp");

这给了我一个进程列表,但是在Process类中似乎没有一种方法可以确定谁拥有该进程?关于如何执行此操作的任何想法?


阅读 290

收藏
2020-05-19

共1个答案

一尘不染

您可以使用WMI来使用户拥有某个进程。要使用WMI,您需要在项目中添加对的引用System.Management.dll

按进程ID:

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

按进程名称 (仅查找第一个进程,进行相应调整):

public string GetProcessOwner(string processName)
{
    string query = "Select * from Win32_Process Where Name = \"" + processName + "\"";
    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
            string owner = argList[1] + "\\" + argList[0];
            return owner;       
        }
    }

    return "NO OWNER";
}
2020-05-19