I found the following method to get a process's owner:
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)
{
return argList[1] + "\\" + argList[0];
}
}
return "";
}
This works fine, however it is very slow. I use it in conjunction with Process.GetProcesses()
and it takes circa 20 seconds in total to get every process owner. Is there any way to speed this up?