如何在C#中找到给定进程的所有者?System.Diagnostics.Process类似乎没有任何属性或方法可以获取此信息.我认为它必须是可用的,因为它显示在Windows任务管理器的"用户名"列下.
我的具体方案涉及查找作为"本地服务"运行的进程实例(例如taskhost.exe).我知道如何使用找到taskhost的所有实例
Process.GetProcessesByName("taskhost")
所以现在我只需要知道如何识别作为本地服务运行的那个.
使用WMI检索Win32_Process类的实例,然后在每个实例上调用GetOwner方法以获取运行该进程的用户的域名和用户名.添加对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... } }