获得在C#中登录的用户名 [英] Get the logged on user name in C#

查看:1367
本文介绍了获得在C#中登录的用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获取当前登录的用户名在Windows 7(即谁是实际登录到控制台,用户在其中,我正在启动正在运行的程序)。

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).

例如,如果我登录为MainUser和SubUser跑我的控制台应用程序(即会显示登录的用户名),则该程序只为当前登录的用户返回SubUser

For example if i am logged on as "MainUser" and run my console application (that will display the logged on user name) as "SubUser", then the program only returns "SubUser" as the currently logged on user.

我用下面两种技术来获取用户名。两者都没有得到我,我想要的东西。

I used the following 2 techniques to get the user name. Both are not getting me the thing that i want.

System.Environment.GetEnvironmentVariable("USERNAME")
System.Security.Principal.WindowsIdentity.GetCurrent().User;

请注意,但是,这V​​BScript代码返回登录的用户名,不论用户帐户作为此脚本的运行:

Note that however, this VBScript code returns the logged on user name irrespective of the user account from which this script is run:

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

任何方法,可以在C#?

Any way it is possible in C#?

推荐答案

我觉得只是转换WMI调用C#为我的作品就好了。

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());
            }

这篇关于获得在C#中登录的用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆