Home > Backend Development > C++ > How Can I Get the Owner of a Process in C# Using WMI?

How Can I Get the Owner of a Process in C# Using WMI?

DDD
Release: 2025-01-17 11:36:09
Original
861 people have browsed it

How Can I Get the Owner of a Process in C# Using WMI?

Get process owner in C#

Accurate control and security management require access to process owner information. This article describes a method to obtain the owner of a process using Windows Management Instrumentation (WMI).

First, you need to quote System.Management.dll. This will allow you to use the WMI framework.

Get owner by process ID

The following code snippet gets the owner of a process based on its process ID:

<code class="language-csharp">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)
        {
            // 返回 DOMAIN\user 格式
            return argList[1] + "\" + argList[0];
        }
    }

    return "NO OWNER";
}</code>
Copy after login

Get owner by process name

To get the owner by process name, you can use the following code snippet:

<code class="language-csharp">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)
        {
            // 返回 DOMAIN\user 格式
            string owner = argList[1] + "\" + argList[0];
            return owner;
        }
    }

    return "NO OWNER";
}</code>
Copy after login

By using WMI, you can effectively determine the owner of a process, gaining flexibility and security in managing system resources.

The above is the detailed content of How Can I Get the Owner of a Process in C# Using WMI?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template