如何在 C# 中找到给定进程的所有者? System.Diagnostics.Process 类似乎没有任何可以获取此信息的属性或方法。我认为它一定可用,因为它显示在 Windows 任务管理器中的“用户名”列下。
我的具体场景涉及查找作为“本地服务”运行的进程实例(例如 taskhost.exe)。我知道如何使用
找到 taskhost 的所有实例Process.GetProcessesByName("taskhost")
所以现在我只需要知道如何识别作为本地服务运行的服务。
最佳答案
使用 WMI 检索 Win32_Process class 的实例, 然后调用 GetOwner method在每个实例上获取运行该进程的用户的域名和用户名。添加对 System.Management 的引用后汇编,下面的代码应该让你开始:
// The call to InvokeMethod below will fail if the Handle property is not retrieved
string[] propertiesToSelect = new[] { "Handle", "ProcessId" };
SelectQuery processQuery = new SelectQuery("Win32_Process", "Name = 'taskhost.exe'", propertiesToSelect);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(processQuery))
using (ManagementObjectCollection processes = searcher.Get())
foreach (ManagementObject process in processes)
{
object[] outParameters = new object[2];
uint result = (uint) process.InvokeMethod("GetOwner", outParameters);
if (result == 0)
{
string user = (string) outParameters[0];
string domain = (string) outParameters[1];
uint processId = (uint) process["ProcessId"];
// Use process data...
}
else
{
// Handle GetOwner() failure...
}
}
关于c# - 如何在 .net 中获取进程的用户名或所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/566835/