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

如何使用C#在.NET中获取当前用户名?,c#,.net,C#,.net,如何使用C#在.NET中获取当前用户名?请尝试以下属性:。使用: System.Security.Principal.WindowsIdentity.GetCurrent().Name 这将是登录名。您还可以尝试使用: Environment.UserName; 像这样…: string j = "Your WindowsXP Account Name is: " + Environment.UserName; 希望这对您有所帮助。如果您在用户网络中,则用户名将不同: Environmen

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

请尝试以下属性:。

使用:

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

这将是登录名。

您还可以尝试使用:

Environment.UserName;
像这样…:

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

希望这对您有所帮助。

如果您在用户网络中,则用户名将不同:

Environment.UserName
- Will Display format : 'Username'
而不是

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

选择所需的格式。

Environment.UserName的文档似乎有点冲突:

同一页上写着:

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

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


如果您使用RunAs测试Environment.UserName,它将为您提供RunAs用户帐户名,不是最初登录到Windows的用户。

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

以下是代码(但不在C中):

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


我尝试了几种现有答案的组合,但他们给了我答案

DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool
我最终使用了

string vUserName = User.Identity.Name;

这只给了我实际的用户域用户名。

我完全赞同其他答案,但我想强调另一种方法,即

String UserName = Request.LogonUserIdentity.Name;
上述方法返回的用户名格式为:DomainName\username。例如,EUROPE\UserName

这与:

String UserName = Environment.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);
    }
}
使用系统;
类样本
{
公共静态void Main()
{
Console.WriteLine();
//  
WriteLine(“用户名:{0}”,Environment.UserName);
}
}

我尝试了前面的所有答案,在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;
}
受保护的字符串GetLoggedInUsername()
{
字符串UserName=System.Security.Principal.WindowsIdentity.GetCurrent().Name;//授予NT权限\System
字符串UserName2=Request.LogonUserIdentity.Name;//授予NT权限\SYSTEM
字符串UserName3=Environment.UserName;//提供系统
字符串UserName4=HttpContext.Current.User.Identity.Name;//给出实际登录的用户(如中所示)
字符串UserName5=System.Windows.Forms.SystemInformation.UserName;//提供系统
返回用户名4;
}
调用此函数将返回登录的用户名


更新:我想指出,在本地服务器实例上运行这段代码会显示Username4返回“”(一个空字符串),但UserName3和UserName5返回登录的用户。需要注意的是。

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

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;
        }
    }
}
试试这个

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
ManagementObjectSearcher searcher=newmanagementobjectsearcher(“从Win32\u计算机系统中选择用户名”);
ManagementObjectCollection集合=searcher.Get();
字符串用户名=(字符串)collection.Cast().First()[“username”];

现在它看起来更好了

,以防有人在寻找用户显示名,而不是像我这样的用户名

这是招待:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName


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

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

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

String myUserName = Environment.UserName

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

我在这里查看了大部分答案,但没有一个给了我正确的用户名

在我的例子中,我想在从其他用户运行我的应用程序时获得登录用户名,比如shift+右键单击文件并“以其他用户身份运行”

我尝试的答案给了我“其他”用户名

这篇博文提供了一种获取登录用户名的方法,即使在我的场景中也可以使用:

它使用Wtsapi

编辑:博客文章中的基本代码,以防消失,是

将此代码添加到从ServiceBase继承的类中

如果您还没有构造函数,请在类中添加一个构造函数;并将此行添加到其中:


这与
Environment.UserName
有何不同?@SimonGillbee,这是错误的,
Environment.UserName
将返回“RunAs”用户。要验证<代码>MessageBox.Show(Environment.UserName)将其放入您的
窗口\u loaded
事件中,并使用RunAs运行它……这将返回
域\用户名
。如何获取与用户名关联的名称?或者,
string username=Environment.username警告:正如Simon Gillbee在接受答案的评论中提到的那样,
Environment.UsernName
给出了登录的帐户名,但是
WindowsIdentity.GetC
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;
        }
    }
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
String myUserName = Environment.UserName
[DllImport("Wtsapi32.dll")]
private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);
[DllImport("Wtsapi32.dll")]
private static extern void WTSFreeMemory(IntPtr pointer);
 
private enum WtsInfoClass
{
    WTSUserName = 5, 
    WTSDomainName = 7,
}
 
private static string GetUsername(int sessionId, bool prependDomain = true)
{
    IntPtr buffer;
    int strLen;
    string username = "SYSTEM";
    if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1)
    {
        username = Marshal.PtrToStringAnsi(buffer);
        WTSFreeMemory(buffer);
        if (prependDomain)
        {
            if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1)
            {
                username = Marshal.PtrToStringAnsi(buffer) + "\\" + username;
                WTSFreeMemory(buffer);
            }
        }
    }
    return username;
}
CanHandleSessionChangeEvent = true;