如何获得用户名在.NET过程的部分或所有者 [英] How to get the user name or owner of a process in .net

查看:123
本文介绍了如何获得用户名在.NET过程的部分或所有者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何才能找到在C#中一个给定的进程的所有者?类的System.Diagnostics.Process似乎没有任何属性或方法,将让我这个信息。我想,这一定是可用的,因为它是在用户名栏显示在Windows任务管理器。

How can I find the owner of a given process in C#? The class System.Diagnostics.Process doesn't seem to have any properties or methods that will get me this information. I figure it must be available because it is shown in the Windows Task Manager under the "User Name" column.

我的具体方案涉及找到的处理(如taskhost.exe),其运行为本地服务的实例。我知道如何找到使用taskhost的所有实例

My specific scenario involves finding the instance of a process (such as taskhost.exe) which is running as "Local Service". I know how to find all the instances of taskhost using

Process.GetProcessesByName("taskhost")

所以,现在我只需要知道如何确定哪些正在作为本地服务的人。

So now I just need to know how to identify the one which is running as local service.

推荐答案

使用WMI检索实例Win32_Process类,然后调用上的每个实例的 GetOwner方法获得域名和该用户的用户名在其下处理正在运行。增加一个参考 System.Management 组装完成后,下面的code应该让你开始:

Use WMI to retrieve instances of the Win32_Process class, then call the GetOwner method on each instance to get the domain name and user name of the user under which the process is running. After adding a reference to the System.Management assembly, the following code should get you started:

// 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...
        }
    }

这篇关于如何获得用户名在.NET过程的部分或所有者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆