如何在 C# 中确定进程的所有者? [英] How do I determine the owner of a process in C#?
问题描述
我正在寻找名为MyApp.exe"的进程,并且我想确保我获得了特定用户拥有的进程.
I am looking for a process by the name of "MyApp.exe" and I want to make sure I get the process that is owned by a particular user.
我使用以下代码获取进程列表:
I use the following code to get a list of the processes:
Process[] processes = Process.GetProcessesByName("MyApp");
这给了我一个进程列表,但在 Process 类中似乎没有办法确定谁拥有该进程?关于我如何做到这一点的任何想法?
This gives me a list of processes, but there does not appear to be a way in the Process class to determine who owns that process? Any thoughts on how I can do this?
推荐答案
您可以使用 WMI 来让用户拥有某个进程.要使用 WMI,您需要向项目添加对 System.Management.dll
的引用.
You can use WMI to get the user owning a certain process. To use WMI you need to add a reference to the System.Management.dll
to your project.
按进程 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 DOMAINuser
return argList[1] + "\" + argList[0];
}
}
return "NO OWNER";
}
按进程名称(仅查找第一个进程,相应调整):
By process name (finds the first process only, adjust accordingly):
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 DOMAINuser
string owner = argList[1] + "\" + argList[0];
return owner;
}
}
return "NO OWNER";
}
这篇关于如何在 C# 中确定进程的所有者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!