如何从C#中当前登录用户的Active Directory中获取专有名称?
答案 0 :(得分:9)
检查以下代码段。您已从IPrincipal转到Identity.Name
。我假设用户已经在Active Directory中进行了身份验证(即使用标准的IIS授权方法)。
private string GetUserName(string identity)
{
if (identity.Contains("\\"))
{
string[] identityList = identity.Split('\\');
return identityList[1];
}
else
{
return identity;
}
}
public string GetUserDn(string identity)
{
var userName = GetUserName(identity);
using (var rootEntry = new DirectoryEntry("LDAP://" + adConfiguration.ServerAddress, null, null, AuthenticationTypes.Secure))
{
using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(sAMAccountName={0})", userName)))
{
var searchResult = directorySearcher.FindOne();
if (searchResult != null)
{
using (var userEntry = searchResult.GetDirectoryEntry())
{
return (string)userEntry.Properties["distinguishedName"].Value;
}
}
}
}
return null;
}
答案 1 :(得分:2)
为什么不使用:System.DirectoryServices.AccountManagement.UserPrincipal.Current.DistinguishedName