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


当前回答

下面是代码(但不是c#):

Private m_CurUser As String

Public ReadOnly Property CurrentUser As String
    Get
        If String.IsNullOrEmpty(m_CurUser) Then
            Dim who As System.Security.Principal.IIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()

            If who Is Nothing Then
                m_CurUser = Environment.UserDomainName & "\" & Environment.UserName
            Else
                m_CurUser = who.Name
            End If
        End If
        Return m_CurUser
    End Get
End Property

下面是代码(现在也是c#):

private string m_CurUser;

public string CurrentUser
{
    get
    {
        if(string.IsNullOrEmpty(m_CurUser))
        {
            var who = System.Security.Principal.WindowsIdentity.GetCurrent();
            if (who == null)
                m_CurUser = System.Environment.UserDomainName + @"\" + System.Environment.UserName;
            else
                m_CurUser = who.Name;
        }
        return m_CurUser;
    }
}

其他回答

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

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

使用实际登录用户的System.Windows.Forms.SystemInformation.UserName作为环境。UserName仍然返回当前进程正在使用的帐户。

试试这个属性:Environment.UserName。

Use:

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

这将是登录名。