How do you get the UserName of the owner of a process?

后端 未结 7 1670
迷失自我
迷失自我 2020-12-06 16:28

I\'m trying to get a list of processes currently owned by the current user (Environment.UserName). Unfortunately, the Process class doesn\'t have a

7条回答
  •  佛祖请我去吃肉
    2020-12-06 17:16

    Props to Andrew Moore for his answer, I'm merely formatting it because it didn't compile in C# 3.5.

    private string GetUserName(string procName)
    {
        string query = "SELECT * FROM Win32_Process WHERE Name = \'" + procName + "\'";
        var procs = new System.Management.ManagementObjectSearcher(query);
        foreach (System.Management.ManagementObject p in procs.Get())
        {
            var path = p["ExecutablePath"];
            if (path != null)
            {
                string executablePath = path.ToString();
                string[] ownerInfo = new string[2];
                p.InvokeMethod("GetOwner", (object[])ownerInfo);
                return ownerInfo[0];
            }
        }
        return null;
    }
    

提交回复
热议问题