Get the logged on user name in C#

前端 未结 4 1552
深忆病人
深忆病人 2020-12-19 03:32

How do i get the current logged on user name in windows 7 (i.e the user who is physically logged on to the console in which the program that i am launching is running).

相关标签:
4条回答
  • 2020-12-19 03:49

    Altough I don't understand if you want to get the user name, who is logged on the system or the user name under which the console is running - maybe you could try using System.Environment.UserName - MSDN claims that it shows the logged on user name.

    0 讨论(0)
  • 2020-12-19 04:07

    You want the user name of your session. You can find out your session ID by calling ProcessIdToSessionId. Then use WTSQuerySessionInformation to find out the user name.

    0 讨论(0)
  • 2020-12-19 04:11

    I think just converting the WMI calls to c# works just fine for me.

                ConnectionOptions oConn = new ConnectionOptions();
                System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);
    
    
                System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");
                ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
                ManagementObjectCollection oReturnCollection = oSearcher.Get();
    
                foreach (ManagementObject oReturn in oReturnCollection) {
                    Console.WriteLine(oReturn["UserName"].ToString().ToLower());
                }
    
    0 讨论(0)
  • 2020-12-19 04:13

    I think you'd have to go down a P/Invoke route. You need to find out which WindowStation your process is running within, and then determine the owner of that WindowStation. I don't think that there's a .NET api for determining these things.

    Win32 APIs that you'd need to look at, are probably GetProcessWindowStation and GetUserObjectSecurity to find the owner.

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