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


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

试试这个属性:Environment.UserName。


Use:

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'

选择您想要的格式。


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

环境。用户名属性

在同一页上写着:

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

AND

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

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


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


下面是代码(但不是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;
    }
}

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

DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool

最后我用了

string vUserName = User.Identity.Name;

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


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

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);
    }
}

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


对于要分发给几个用户的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"];

现在看起来好多了


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

下面是奖励:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

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


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

当我把它改成system . security . principal . windowidentity . getcurrent()时,它很高兴。但是我最终使用了Environment.UserName;来获取登录的Windows用户,并且没有域部分。


String myUserName = Environment.UserName

这将为您提供输出- your_user_name


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

在我的情况下,我想获得登录用户名,同时运行我的应用程序从不同的用户,就像shift+右键单击文件和“作为不同的用户运行”。

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

这篇博文提供了一种获取登录用户名的方法,即使在我的场景中也能工作: https://smbadiwe.github.io/post/track-activities-windows-service/

它使用Wtsapi

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

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

[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;

编辑: 每个评论请求,这是我如何获得会话ID -这是活动控制台会话ID:

[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();

var activeSessionId = WTSGetActiveConsoleSessionId();
if (activeSessionId == INVALID_SESSION_ID) //failed
{
    logger.WriteLog("No session attached to console!");    
}