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

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

729477 次浏览
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

试试属性:Environment.UserName

用途:

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操作系统的人员的用户名。

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

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

对于实际登录的用户使用System.Windows.Forms.SystemInformation.UserName,因为Environment.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;

上面的方法返回了格式为域名\用户名的用户名。例如,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);
}
}

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

对于一个将分发给多个用户的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的引用。

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

当我将其更改为System.Security.Principal.WindowsIdentity.GetCurrent().Name时很高兴,但我最终使用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!");
}