我如何获得当前用户名在。net使用c# ?
当前回答
试试这个
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
现在看起来好多了
其他回答
为了对其他人有帮助,当我将一个应用程序从c#.net 3.5 app升级到Visual Studio 2017时,这行代码User.Identity.Name.Substring(4);抛出这个错误“startIndex不能大于字符串长度”(它之前没有阻止)。
当我把它改成system . security . principal . windowidentity . getcurrent()时,它很高兴。但是我最终使用了Environment.UserName;来获取登录的Windows用户,并且没有域部分。
String myUserName = Environment.UserName
这将为您提供输出- your_user_name
我从已有的答案中尝试了几种组合,但它们给了我
DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool
最后我用了
string vUserName = User.Identity.Name;
这给了我实际的用户域用户名。
我完全赞同其他的答案,但我想强调另一个方法,它说
String UserName = Request.LogonUserIdentity.Name;
上述方法返回的用户名格式为:DomainName\ username。例如,EUROPE\UserName
这不同于:
String UserName = Environment.UserName;
显示格式为:UserName
最后:
String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
它给出:NT AUTHORITY\IUSR(在IIS服务器上运行应用程序时)和DomainName\UserName(在本地服务器上运行应用程序时)。
我尝试了之前所有的答案,在MSDN上找到了答案,这些都对我不起作用。见'UserName4'为我正确的一个。
我在登录用户之后,如下所示:
<asp:LoginName ID="LoginName1" runat="server" />
这是我写的一个小函数。我的结果在每行之后的评论中。
protected string GetLoggedInUsername()
{
string UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // Gives NT AUTHORITY\SYSTEM
String UserName2 = Request.LogonUserIdentity.Name; // Gives NT AUTHORITY\SYSTEM
String UserName3 = Environment.UserName; // Gives SYSTEM
string UserName4 = HttpContext.Current.User.Identity.Name; // Gives actual user logged on (as seen in <ASP:Login />)
string UserName5 = System.Windows.Forms.SystemInformation.UserName; // Gives SYSTEM
return UserName4;
}
调用此函数返回登录的用户名。
更新:我想指出的是,在我的本地服务器实例上运行这段代码显示Username4返回“”(空字符串),但UserName3和UserName5返回登录的用户。只是需要注意的事情。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本