在C#中获取登录的用户名

San*_*osh 9 c# login

如何在Windows 7中获取当前登录的用户名(即物理登录到我正在启动的程序正在运行的控制台的用户).

例如,如果我以"MainUser"身份登录并运行我的控制台应用程序(将显示登录的用户名)作为"SubUser",则程序仅返回"SubUser"作为当前登录的用户.

我使用以下两种技术来获取用户名.两者都没有让我得到我想要的东西.

System.Environment.GetEnvironmentVariable("USERNAME")
System.Security.Principal.WindowsIdentity.GetCurrent().User;
Run Code Online (Sandbox Code Playgroud)

但请注意,无论运行此脚本的用户帐户如何,此VBScript代码都会返回登录的用户名:

strComputer = "." 
Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
Set compsys_arr = objWMIService.ExecQuery _ 
    ("Select * from Win32_ComputerSystem") 
For Each sys in compsys_arr
    Wscript.Echo "username: " & sys.UserName
Next
Run Code Online (Sandbox Code Playgroud)

在C#中有什么可能吗?

San*_*osh 6

我认为只需将WMI调用转换为c#就可以了.

            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());
            }
Run Code Online (Sandbox Code Playgroud)


Dam*_*ver 5

我认为你必须走P/Invoke路线.您需要找出您的进程在哪个WindowStation中运行,然后确定该WindowStation的所有者.我认为没有用于确定这些东西的.NET API.

您需要查看的Win32 API可能是GetProcessWindowStationGetUserObjectSecurity来查找所有者.