如何使用C#代码从Windows Active Directory获取当前用户的登录名?
如何使用C#代码从Windows Active Directory获取当前用户的登录名?
简单地说,
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;
正常运作 :)
如果您使用的是 .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中轻松地操作用户和组非常容易!
参考资料:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
做什么?(意思是询问此代码语句的作用) - Ole AlbersSystem.DirectoryServices.AccountManagement.UserPrincipal.Current.Name
其他解决方案提供的是"NT AUTHORITY\NETWORK SERVICE",但System.Threading.Thread.CurrentPrincipal.Identity.Name.ToString()对我有用。
我在我的视图中有这个,对我来说完美无缺!
<h5 class="mb-0 text-gray-800">欢迎,<span style="text-transform:capitalize">@User.Identity.Name.Replace("AD-GROUP-NAME\\", "").Replace(".", " ")</span></h5>