如何使用C#获取.NET中的当前用户名?

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

如何使用c_在.NET中获取当前用户名?


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


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

1
2
Environment.UserName
- Will Display format : 'Username'

而不是

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

选择所需格式。


尝试属性:Environment.UserName。


environment.username的文档似乎有点冲突:

environment.username属性

在同一页上写着:

Gets the user name of the person who is currently logged on to the Windows operating system.

和

displays the user name of the person who started the current thread

如果使用runas测试environment.user name,它将为您提供runas用户帐户名,而不是最初登录到Windows的用户。


我完全排在其他答案的第二位,但我想再强调一个方法

1
String UserName = Request.LogonUserIdentity.Name;

上述方法返回的用户名格式为:域名用户名。例如,欧洲用户名

不同于:

1
String UserName = Environment.UserName;

显示格式为:用户名

最后:

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

给出:NT AUTHORITY\IUSR(在IIS服务器上运行应用程序)和DomainName\UserName(在本地服务器上运行应用程序)。


用途:

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

这将是登录名。


您也可以尝试使用:

1
Environment.UserName;

这样地。。。:

1
string j ="Your WindowsXP Account Name is:" + Environment.UserName;

希望这有帮助。


我从现有答案中尝试了几种组合,但它们给了我

1
2
3
DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool

我最后用了

1
string vUserName = User.Identity.Name;

它只提供了实际用户的域用户名。


对于实际登录的用户使用System.Windows.Forms.SystemInformation.UserName,因为Environment.UserName仍然返回当前进程使用的帐户。


我试过所有以前的答案,在没有一个对我有用之后,我在msdn上找到了答案。请参阅"用户名4",了解适合我的用户名。

我在登录用户之后,显示方式为:

1
 

我写了一个小函数来尝试所有的方法。我的结果在每行后面的注释中。

1
2
3
4
5
6
7
8
9
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返回登录的用户。只是一些需要注意的事情。


以防万一有人在寻找用户名,而不是像我这样的用户名。

以下是款待:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

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


这是代码(但不是C):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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中):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
    }
}

1
String myUserName = Environment.UserName

这将为您提供输出-您的用户名


试试这个

1
2
3
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

现在看起来好多了


对于要分发给多个用户的Windows窗体应用程序(其中许多用户通过VPN登录),我尝试了几种方法,这些方法都适用于我的本地计算机测试,但不适用于其他用户。我偶然看到一篇我改编并工作的微软文章。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Security.Principal;

namespace ManageExclusion
{
    public static class UserIdentity

    {
        // concept borrowed from
        // https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx

        public static string GetUser()
        {
            IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
            WindowsIdentity windowsIdentity = new WindowsIdentity(accountToken);
            return windowsIdentity.Name;
        }
    }
}

获取当前的Windows用户名:

1
2
3
4
5
6
7
8
9
10
11
12
using System;

class Sample
{
    public static void Main()
    {
        Console.WriteLine();

        //  <-- Keep this information secure! -->
        Console.WriteLine("UserName: {0}", Environment.UserName);
    }
}


如果这对其他人有帮助,当我将一个应用程序从C.NET 3.5应用程序升级到Visual Studio 2017时,这行代码User.Identity.Name.Substring(4);抛出了这个错误"startindex不能大于字符串长度"(它以前没有回避)。

当我把它改为System.Security.Principal.WindowsIdentity.GetCurrent().Name时,它很高兴,但是我最终使用Environment.UserName;获得了登录的Windows用户,没有域部分。