我如何获得当前用户名在。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用户,并且没有域部分。

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

环境。用户名属性

在同一页上写着:

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

AND

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

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

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

下面是奖励:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

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

我完全赞同其他的答案,但我想强调另一个方法,它说

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(在本地服务器上运行应用程序时)。

获取当前Windows用户名:

using System;

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

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