Active Directory与DirectorySearcher和PrincipalSearcher的结果不同

时间:2012-08-09 15:46:06

标签: c# search active-directory

在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组

嗯,是这个错误还是我错过了什么?

由于

1 个答案:

答案 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;
        }

抱歉愚蠢的问题。