2

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?

Jonas Kohl
  • 1,018
  • 1
  • 11
  • 28
  • 2
    This API is notoriously slow. If you're getting the owner of every process you might consider removing the `where` clause and iterate over the process list just once. – 500 - Internal Server Error Nov 29 '18 at 10:04
  • ManagementObject is going in to a database which contains the history of of your PC which can be very large. If you need a current process then use following : https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocesses?view=netframework-4.7.2 – jdweng Nov 29 '18 at 10:20
  • @jdweng Did you even fully read my question? – Jonas Kohl Nov 29 '18 at 10:26
  • Why are you using ManagementObject? Search for parent using following : https://stackoverflow.com/questions/2531837/how-can-i-get-the-pid-of-the-parent-process-of-my-application – jdweng Nov 29 '18 at 10:50

0 Answers0