The C# Process
class doesn't directly reveal process ownership. However, we can leverage Windows Management Instrumentation (WMI) to obtain this crucial detail. Remember to add a reference to System.Management.dll
in your project.
This method retrieves the process owner given its ID:
<code class="language-csharp">public string GetProcessOwner(int processId) { string query = $"Select * From Win32_Process Where ProcessID = {processId}"; using (var searcher = new ManagementObjectSearcher(query)) { using (var processList = searcher.Get()) { foreach (ManagementObject obj in processList) { string[] ownerInfo = new string[2]; int result = Convert.ToInt32(obj.InvokeMethod("GetOwner", ownerInfo)); if (result == 0) { return $"{ownerInfo[1]}\{ownerInfo[0]}"; // DOMAIN\user format } } } } return "NO OWNER"; }</code>
This alternative uses the process name to find the owner:
<code class="language-csharp">public string GetProcessOwner(string processName) { string query = $"Select * from Win32_Process Where Name = '{processName}'"; using (var searcher = new ManagementObjectSearcher(query)) { using (var processList = searcher.Get()) { foreach (ManagementObject obj in processList) { string[] ownerInfo = new string[2]; int result = Convert.ToInt32(obj.InvokeMethod("GetOwner", ownerInfo)); if (result == 0) { return $"{ownerInfo[1]}\{ownerInfo[0]}"; // DOMAIN\user format } } } } return "NO OWNER"; }</code>
These functions provide a robust way to determine process ownership, offering valuable insights for system administration and security analysis. The use of using
statements ensures proper resource disposal.
The above is the detailed content of How to Find the Owner of a Process in C# Using WMI?. For more information, please follow other related articles on the PHP Chinese website!