Home >Backend Development >C++ >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>
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>
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!