我如何获得当前用户名在。net使用c# ?


当前回答

我尝试了之前所有的答案,在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返回登录的用户。只是需要注意的事情。

其他回答

Use:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

这将是登录名。

如果你在一个用户网络中,那么用户名将是不同的:

Environment.UserName
- Will Display format : 'Username'

而不是

System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'

选择您想要的格式。

环境文档。UserName似乎有点矛盾:

环境。用户名属性

在同一页上写着:

获取当前登录到Windows操作系统的用户的用户名。

AND

显示启动当前线程的用户名

如果您测试环境。UserName使用RunAs,它会给你RunAs用户帐户名,而不是最初登录Windows的用户。

以防有人在找用户显示名而不是用户名,比如我。

下面是奖励:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

在项目中添加对System.DirectoryServices.AccountManagement的引用。

为了对其他人有帮助,当我将一个应用程序从c#.net 3.5 app升级到Visual Studio 2017时,这行代码User.Identity.Name.Substring(4);抛出这个错误“startIndex不能大于字符串长度”(它之前没有阻止)。

当我把它改成system . security . principal . windowidentity . getcurrent()时,它很高兴。但是我最终使用了Environment.UserName;来获取登录的Windows用户,并且没有域部分。