在C#中查询Active Directory时遇到奇怪的问题。
var ctx = new PrincipalContext(ContextType.Domain, "adr", "usr", "pwd");
var entry = new DirectoryEntry("LDAP://" + adr, usr, pwd);
var searcher = new DirectorySearcher(entry) { Filter = "(&(sAMAccountName=user_to_search))", PageSize = 2000 };
foreach (SearchResult searchUser in searcher.FindAll())
{
// groups
var groups = searchUser.GetPropertyValues("memberof");
}
var groups = UserPrincipal.FindByIdentity(ctx, "usr_to_search").GetGroups(ctx).ToList();
但结果并不相同:
PrincipalSearcher
返回14组DirectorySearcher
返回12组嗯,是这个错误还是我错过了什么?
由于
答案 0 :(得分:2)
天啊,我的扩展方法错误( i< prop.count - 1 )。
public static List<string> GetPropertyValues(this SearchResult searchResult,string property)
{
var prop = searchResult.Properties[property];
var results = new List<string>();
if (prop != null && prop.Count > 0)
{
for (int i = 0; i < prop.Count - 1; i++)
{
results.Add(prop[i].ToString());
}
}
return results;
}
抱歉愚蠢的问题。