tags:

views:

1342

answers:

4

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.

+2  A: 

You might look at using System.Management (WMI). With that you can query the Win32_Process tree.

palehorse
+2  A: 

here is the MS link labelled "GetOwner Method of the Win32_Process Class"

Oskar
+2  A: 

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.

Martin Hollingsworth
+1  A: 

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.Item("ExecutablePath") != null) {
                string ExecutablePath = Process.Item("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();
    }
}
Andrew Moore