How do I get the current username in .NET using C#?

后端 未结 18 1844
忘了有多久
忘了有多久 2020-11-22 09:59

How do I get the current username in .NET using C#?

18条回答
  •  猫巷女王i
    2020-11-22 10:05

    Here is the code (but not in 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
    

    Here is the code (now also in 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;
        }
    }
    

提交回复
热议问题