Home  >  Article  >  Backend Development  >  C# Get the user name of the system process

C# Get the user name of the system process

黄舟
黄舟Original
2016-12-22 13:58:451783browse

You need to add a reference to System.Management.dll

using System.Diagnostics; 
using System.Management;static void Main(string[] args) 
{ 
foreach (Process p in Process.GetProcesses()) 
{ 
Console.Write(p.ProcessName); 
Console.Write("----"); 
Console.WriteLine(GetProcessUserName(p.Id)); 
} 
Console.ReadKey(); 
}private static string GetProcessUserName(int pID) 
{ 
string text1 = null; 
SelectQuery query1 = new SelectQuery("Select * from Win32_Process WHERE processID=" + pID); 
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1); 
try 
{ 
foreach (ManagementObject disk in searcher1.Get()) 
{ 
ManagementBaseObject inPar = null; 
ManagementBaseObject outPar = null; 
inPar = disk.GetMethodParameters("GetOwner"); 
outPar = disk.InvokeMethod("GetOwner", inPar, null); 
text1 = outPar["User"].ToString(); 
break; 
} 
} 
catch 
{ 
text1 = "SYSTEM"; 
} 
return text1; 
}

The above is the content of C# to obtain the user name of the system process. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
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