How do you get the UserName of the owner of a process?

后端 未结 7 1657
迷失自我
迷失自我 2020-12-06 16:28

I\'m trying to get a list of processes currently owned by the current user (Environment.UserName). Unfortunately, the Process class doesn\'t have a

相关标签:
7条回答
  • 2020-12-06 17:03

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

    0 讨论(0)
  • 2020-12-06 17:10

    You'll need to add a reference to System.Management.dll for this to work.

    Here's what I ended up using. It works in .NET 3.5:

    using System.Linq;
    using System.Management;
    
    class Program
    {
        /// <summary>
        /// Adapted from https://www.codeproject.com/Articles/14828/How-To-Get-Process-Owner-ID-and-Current-User-SID
        /// </summary>
        public static void GetProcessOwnerByProcessId(int processId, out string user, out string domain)
        {
            user = "???";
            domain = "???";
    
            var sq = new ObjectQuery("Select * from Win32_Process Where ProcessID = '" + processId + "'");
            var searcher = new ManagementObjectSearcher(sq);
            if (searcher.Get().Count != 1)
            {
                return;
            }
            var process = searcher.Get().Cast<ManagementObject>().First();
            var ownerInfo = new string[2];
            process.InvokeMethod("GetOwner", ownerInfo);
    
            if (user != null)
            {
                user = ownerInfo[0];
            }
            if (domain != null)
            {
                domain = ownerInfo[1];
            }
        }
    
        public static void Main()
        {
            var processId = System.Diagnostics.Process.GetCurrentProcess().Id;
            string user;
            string domain;
            GetProcessOwnerByProcessId(processId, out user, out domain);
            System.Console.WriteLine(domain + "\\" + user);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 17:12

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

    0 讨论(0)
  • 2020-12-06 17:16

    Props to Andrew Moore for his answer, I'm merely formatting it because it didn't compile in C# 3.5.

    private string GetUserName(string procName)
    {
        string query = "SELECT * FROM Win32_Process WHERE Name = \'" + procName + "\'";
        var procs = new System.Management.ManagementObjectSearcher(query);
        foreach (System.Management.ManagementObject p in procs.Get())
        {
            var path = p["ExecutablePath"];
            if (path != null)
            {
                string executablePath = path.ToString();
                string[] ownerInfo = new string[2];
                p.InvokeMethod("GetOwner", (object[])ownerInfo);
                return ownerInfo[0];
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-12-06 17:23

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-06 17:25

    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.

    0 讨论(0)
提交回复
热议问题