I'm trying to get a list of processes currently owned by the current user (Environment.UserName
). Unfortunately, the Process
class doesn't have any way of getting the UserName of the user owning a process.
How do you get the UserName of the user which is the owner of a process using the Process
class so I can compare it to Environment.UserName
?
If your solution requires a pinvoke
, please provide a code example.
Open the terminal window or app. To see only the processes owned by a specific user on Linux run: ps -u {USERNAME} Search for a Linux process by name run: pgrep -u {USERNAME} {processName} Another option to list processes by name is to run either top -U {userName} or htop -u {userName} commands.
The /proc/<pid>/loginuid file has the uid number of the user running the process; id -nu reads uid from stdin and returns a user name. Nice.
To view all processes on the system, you can execute:ps -f.
Thanks, your answers put me on the proper path. For those who needs a code sample:
public class App
{
public static void Main(string[] Args)
{
Management.ManagementObjectSearcher Processes = new Management.ManagementObjectSearcher("SELECT * FROM Win32_Process");
foreach (Management.ManagementObject Process in Processes.Get()) {
if (Process["ExecutablePath"] != null) {
string ExecutablePath = Process["ExecutablePath"].ToString();
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[]) OwnerInfo);
Console.WriteLine(string.Format("{0}: {1}", IO.Path.GetFileName(ExecutablePath), OwnerInfo[0]));
}
}
Console.ReadLine();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With