我如何获得当前用户名在。net使用c# ?
当前回答
下面是代码(但不是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;
}
}
其他回答
我完全赞同其他的答案,但我想强调另一个方法,它说
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(在本地服务器上运行应用程序时)。
我看了这里的大部分答案,没有一个给我正确的用户名。
在我的情况下,我想获得登录用户名,同时运行我的应用程序从不同的用户,就像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!");
}
获取当前Windows用户名:
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
// <-- Keep this information secure! -->
Console.WriteLine("UserName: {0}", Environment.UserName);
}
}
以防有人在找用户显示名而不是用户名,比如我。
下面是奖励:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
在项目中添加对System.DirectoryServices.AccountManagement的引用。
我尝试了之前所有的答案,在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返回登录的用户。只是需要注意的事情。
推荐文章
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- MSBuild路径
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException