gpt4 book ai didi

c# - 如何在 .net 中获取进程的用户名或所有者

转载 作者:行者123 更新时间:2023-11-30 13:53:17 50 4
gpt4 key购买 nike

如何在 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/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com