如何确定在C#程序的所有者? [英] How do I determine the owner of a process in C#?

查看:75
本文介绍了如何确定在C#程序的所有者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找由MyApp.exe将名称的过程,我想确保我得到一个由特定用户所拥有的过程。

I am looking for a process by the name of "MyApp.exe" and I want to make sure I get the process that is owned by a particular user.

我使用以下code键得到的处理的列表:

I use the following code to get a list of the processes:

Process[] processes = Process.GetProcessesByName("MyApp");

这给我的进程列表,但不会出现在Process类的方式来决定谁拥有该进程呢?我如何能做到这一点有什么想法?

This gives me a list of processes, but there does not appear to be a way in the Process class to determine who owns that process? Any thoughts on how I can do this?

推荐答案

您可以使用WMI来获取用户拥有一定的过程。要使用WMI,你需要到 System.Management.dll 引用添加到您的项目。

You can use WMI to get the user owning a certain process. To use WMI you need to add a reference to the System.Management.dll to your project.

通过进程ID:

public string GetProcessOwner(int processId)
{
    string query = "Select * From Win32_Process Where ProcessID = " + processId;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get();

    foreach (ManagementObject obj in processList)
    {
        string[] argList = new string[] { string.Empty, string.Empty };
        int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
        if (returnVal == 0)
        {
            // return DOMAIN\user
            return argList[1] + "\\" + argList[0];
        }
    }

    return "NO OWNER";
}

通过进程名称(只找到第一个进程,相应调整):

By process name (finds the first process only, adjust accordingly):

public string GetProcessOwner(string processName)
{
    string query = "Select * from Win32_Process Where Name = \"" + processName + "\"";
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get();

    foreach (ManagementObject obj in processList)
    {
        string[] argList = new string[] { string.Empty, string.Empty };
        int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
        if (returnVal == 0)
        {
            // return DOMAIN\user
            string owner = argList[1] + "\\" + argList[0];
            return owner;       
        }
    }

    return "NO OWNER";
}

这篇关于如何确定在C#程序的所有者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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