使用C#代码从Active Directory获取当前登录用户

33

如何使用C#代码从Windows Active Directory获取当前用户的登录名?

5个回答

63

简单地说,

string Name = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()).Identity.Name;

或者

string Name = System.Environment.UserName  

或者

string Name = Environment.GetEnvironmentVariable("USERNAME");

或者

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

正常运作 :)


12
这里涉及到的AD完全没有用处(登录后它不会跟踪当前用户,也不会在会话期间频繁使用)。 - TomTom
8
我有一个网站,想获取已登录用户的用户名到Windows系统,但上述方法都没有给我想要的结果 :/ - SearchForKnowledge
3
非常感谢。我一直在寻找。 - Marty_in_a_Box
3
@Sunil,你取消了我的答案,有什么我能帮忙的吗? - Ahmed Ghoneim
1
你太棒了!谢谢! - dchamb
考虑使用驼峰命名法变量名称? - Lei Yang

33

如果您使用的是 .NET 3.5 及以上版本,则可以使用以下方法:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find current user
UserPrincipal user = UserPrincipal.Current;

if(user != null)
{
   string loginName = user.SamAccountName; // or whatever you mean by "login name"
}    

新的S.DS.AM使得在AD中轻松地操作用户和组非常容易!

参考资料:


4
这适用于任何已经安装了Active Directory的环境。 - marc_s
1
嗨,它在域内运行正常。如何使其在不同的服务器或域外工作? - Sunil Mathari
4
正如我之前所说,这只适用于使用Active Directory的情况。如果没有AD,则无法使其工作。不清楚您所说的“在不同服务器中”是什么意思 - 它使用默认的Active Directory DOMAIN运行,因此它与特定服务器无关。 - marc_s
5
当“ctx”未被使用时,需要PrincipalContext ctx = new PrincipalContext(ContextType.Domain);做什么?(意思是询问此代码语句的作用) - Ole Albers
6
在这种特定情况下,你不需要它。如果你想通过某个名字搜索用户,那么你需要上下文。 - marc_s
显示剩余2条评论

3
System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name

这对我也有效!谢谢。

2

其他解决方案提供的是"NT AUTHORITY\NETWORK SERVICE",但System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString()对我有用。


0

我在我的视图中有这个,对我来说完美无缺!

<h5 class="mb-0 text-gray-800">欢迎,<span style="text-transform:capitalize">@User.Identity.Name.Replace("AD-GROUP-NAME\\", "").Replace(".", " ")</span></h5>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接