You can use WMI to get the user owning a certain process. To use WMI you need to add a reference to the System.Management.dll
to your project.
By process id:
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 DOMAINuser
return argList[1] + "" + argList[0];
}
}
return "NO OWNER";
}
By process name (finds the first process only, adjust accordingly):
public string GetProcessOwner(string processName)
{
string query = "Select * from Win32_Process Where Name = "" + processName + """;
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 DOMAINuser
string owner = argList[1] + "" + argList[0];
return owner;
}
}
return "NO OWNER";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…