繁体   English   中英

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

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

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

选项 A)

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
  • 返回:网络名称\用户名
  • 获取用户的 Windows 登录名。
  • 详细信息: https ://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity

选项 B)

string userName = Environment.UserName
  • 返回:用户名
  • 获取与当前线程关联的人员的用户名。
  • 详细信息: https ://docs.microsoft.com/en-us/dotnet/api/system.environment.username

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

Environment.UserName
- Will Display format : 'Username'

而不是

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

选择您想要的格式。

尝试属性: Environment.UserName

Environment.UserName 的文档似乎有点矛盾:

Environment.UserName 属性

在同一页上它说:

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

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

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

我完全支持其他答案,但我想强调另一种方法,它说

String UserName = Request.LogonUserIdentity.Name;

上述方法以以下格式返回用户名: DomainName\UserName 例如,欧洲\用户名

这不同于:

String UserName = Environment.UserName;

其中显示格式为:用户名

最后:

String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

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

利用:

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

这将是登录名。

String myUserName = Environment.UserName

这会给你输出 - your_user_name

以防万一有人正在寻找用户Display Name而不是User Name ,就像我一样。

这是款待:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName

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

您可能还想尝试使用:

Environment.UserName;

像这样...:

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

希望这对您有所帮助。

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

DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool

我最终使用

string vUserName = User.Identity.Name;

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

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

我已经尝试了所有以前的答案,并在这些都不适合我之后在 MSDN 上找到了答案。 请参阅“用户名 4”以获得正确的我。

我在Logged in User之后,如下所示:

<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 返回登录的用户。 只是需要提防的事情。

尝试这个

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["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;
    }
}

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

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 用户名:

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 用户并且没有域部分。

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

就我而言,我想在从其他用户运行我的应用程序时获取登录的用户名,例如当 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!");    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM