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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10877614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:37:41  来源:igfitidea点击:

Getting current login from Active Directory using C# code

c#.netactive-directory

提问by Sunil Mathari

How can I get the current user's login name from Windows Active Directory using C# code?

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

回答by Ahmed Ghoneim

Simply,

简单地,

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

OR

或者

string Name = System.Environment.UserName  

OR

或者

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

OR

或者

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

works :)

作品:)

回答by marc_s

If you're on .NET 3.5 and up, you can use:

如果您使用的是 .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"
}    

The new S.DS.AM makes it really easy to play around with users and groups in AD!

新的 S.DS.AM 使在 AD 中与用户和组一起玩变得非常容易!

References:

参考:

回答by Singaravelan

System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name

This is also working for me! Thanks

这也对我有用!谢谢

回答by Tel

I was getting "NT AUTHORITY\NETWORK SERVICE" with other solutions offered but System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString()worked for me.

我得到了“NT AUTHORITY\NETWORK SERVICE”以及其他提供的解决方案,但 System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString()为我工作。

回答by N0vice

I have this in my view and works perfectly for me!

我有这个想法,非常适合我!

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

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