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

后端 未结 7 1674
迷失自我
迷失自我 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: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
    {
        /// 
        /// Adapted from https://www.codeproject.com/Articles/14828/How-To-Get-Process-Owner-ID-and-Current-User-SID
        /// 
        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().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);
        }
    }
    

提交回复
热议问题