How do I determine the owner of a process in C#?
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 DOMAIN\user
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 DOMAIN\user
string owner = argList[1] + "\\" + argList[0];
return owner;
}
}
return "NO OWNER";
}
How do you get the UserName of the owner of a process?
The CodeProject article How To Get Process Owner ID and Current User SID by Warlib describes how to do this using both WMI and using the Win32 API via PInvoke.
The WMI code is much simpler but is slower to execute. Your question doesn't indicate which would be more appropriate for your scenario.
How do I find out what user owns what process programmatically?
You can use the Win32_Process class from the WMI to get all the info related to a process.
check this sample
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
public static string GetProcessOwner(int PID, out string User)
{
string DummyStr = String.Empty;
User = String.Empty;
string ProcessStr = String.Empty;
try
{
ObjectQuery WMIQuery = new ObjectQuery(string.Format("Select * from Win32_Process Where ProcessID ={0}", PID.ToString()));
ManagementObjectSearcher WMIResult = new ManagementObjectSearcher(WMIQuery);
if (WMIResult.Get().Count == 0) return DummyStr;
foreach (ManagementObject oItem in WMIResult.Get())
{
string[] List = new String[2];
oItem.InvokeMethod("GetOwner", (object[])List);
ProcessStr = (string)oItem["Name"];
User = List[0];
if (User == null) User = String.Empty;
string[] StrSID = new String[1];
oItem.InvokeMethod("GetOwnerSid", (object[])StrSID);
DummyStr = StrSID[0];
return DummyStr;
}
}
catch
{
return DummyStr;
}
return DummyStr;
}
static void Main(string[] args)
{
string User;
Process[] processList = Process.GetProcesses();
foreach (Process p in processList)
{
GetProcessOwner(p.Id,out User);
Console.WriteLine(p.Id.ToString()+' '+User);
}
Console.ReadLine();
}
}
}
UPDATE
also you can store in a Dictionary the owners and the pid, for improve the performance.
using System;
using System.Diagnostics;
using System.Management;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
public static Dictionary<int, string> GetAllProcessOwners()
{
Dictionary<int, string> d = new Dictionary<int, string>();
//string DummyStr = String.Empty;
string User = String.Empty;
string ProcessStr = String.Empty;
try
{
ObjectQuery WMIQuery = new ObjectQuery("Select * from Win32_Process");
ManagementObjectSearcher WMIResult = new ManagementObjectSearcher(WMIQuery);
if (WMIResult.Get().Count == 0) return d;
foreach (ManagementObject oItem in WMIResult.Get())
{
string[] List = new String[2];
oItem.InvokeMethod("GetOwner", (object[])List);
ProcessStr = (string)oItem["Name"];
User = List[0];
if (User == null) User = String.Empty;
//string[] StrSID = new String[1];
//oItem.InvokeMethod("GetOwnerSid", (object[])StrSID);
//DummyStr = StrSID[0];
d.Add(Convert.ToInt32(oItem["ProcessId"]), User);
}
}
catch (Exception E)
{
Console.WriteLine(E.Message);
return d;
}
return d;
}
static void Main(string[] args)
{
Dictionary<int, string> List = GetAllProcessOwners();
Process[] processList = Process.GetProcesses();
foreach (Process p in processList)
{
if (List.ContainsKey(p.Id))
{
Console.WriteLine(p.Id.ToString() + ' ' + List[p.Id]);
}
}
Console.ReadLine();
}
}
}
Related Topics
Is There a Way of Setting Culture for a Whole Application? All Current Threads and New Threads
How to Change Network Settings (Ip Address, Dns, Wins, Host Name) with Code in C#
#If Debug VS. Conditional("Debug")
How to Split a String by a Multi-Character Delimiter in C#
Does Using "New" on a Struct Allocate It on the Heap or Stack
Detailed Explanation of Variable Capture in Closures
Deep Null Checking, Is There a Better Way
Xml Serialization and Namespace Prefixes
How to Compare 2 Files Fast Using .Net
System.Missingmethodexception: Method Not Found
How to Add System.Windows.Interactivity to Project
How to Make a .Net Windows Forms Application That Only Runs in the System Tray
What Guarantees Are There on the Run-Time Complexity (Big-O) of Linq Methods
Associating Enums with Strings in C#