我正在尝试从 Active Directory 中检索用户名。我找到了这段代码来尝试,但是它无法识别 User.Identity.Name
的 User
部分。我查看是否需要添加另一个引用或程序集,但我没有看到任何东西。有没有更好的方法从 Active Directory 获取用户名?
static string GetUserName(){
string name = "";
using (var context = new PrincipalContext(ContextType.Domain))
{
var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name);
if (usr != null)
name = usr.DisplayName;
}
}
最佳答案
您可以使用 WindowsIdentity.GetCurrent
using System.Security.Principal;
static string GetUserName()
{
WindowsIdentity wi = WindowsIdentity.GetCurrent();
string[] parts = wi.Name.Split('\\');
if(parts.Length > 1) //If you are under a domain
return parts[1];
else
return wi.Name;
}
用法:
string fullName = GetUserName();
很高兴为您服务!
关于c# - 从 Active Directory 检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40771469/