I am trying to print all running processes in C#, similarly to how tasklist
or ps
does. I tried it with the following code:
foreach(Process process in Process.GetProcesses()) {
if(!process.HasExited) {
Console.WriteLine(process.ProcessName);
}
}
But with it, I run into some issues on Windows (did not try it on Linux):
- When I execute the above code with user-privileges, it only prints processes started by this user. If I run it as administrator, all processes are printed.
- When I open a cmd window with user privileges and list the processes (i.e. execute
tasklist
), all processes are printed, even those started by the system / by an administrator account.
Is there a way to get all processes, even those started by a higher privileged user, without requiring the program to be run as administrator?
One solution came to my mind:
System.Diagnostics.Process.Start("CMD.exe", "tasklist > C:\file.txt");
String[] processes = File.ReadAllLines(@"C:\file.txt");
But this is really hacky and does not work on linux.