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

标签 c# .net process

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

相关文章:

.net - 重用 IEnumerable<T> 会导致错误结果,例如任何()

c# - 如何打开特定编码类型的ShareFileClient写入流?

c - 如何在 C 中创建一个在父进程死亡后运行的进程?

ruby-on-rails - 如何为非 Web 前端进程设置监控?

linux - UNIX(或LINUX)中的退出和等待函数

c# - 如何检查泛型类型参数是否可为空?

c# - Tesseract 3.02 无法加载 DLL

.net - 犀牛模拟 : override a stubbed property

c# - 代码首先,EF 4.1 : What is the best way to map the following classes with a database. ..?

无事件的 C# WPF 序列化 XAML