C#获取进程对应的用户名
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 userName = string.Empty; try { foreach (ManagementObject item in new ManagementObjectSearcher("Select * from Win32_Process WHERE processID=" + pID).Get()) { ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; inPar = item.GetMethodParameters("GetOwner"); outPar = item.InvokeMethod("GetOwner", inPar, null); userName = Convert.ToString(outPar["User"]); break; } } catch { userName = "SYSTEM"; } return userName; }