首页 > 解决方案 > DirectorySearcher 不从 LDAP 查询返回任何结果(C#)

问题描述

我正在尝试返回 2 个 OU 中的所有用户。第一个 OU(下图)是 HSD 用户 OU 中的 IT 用户。这每次都返回 null ,但我可以通过以下方式让所有用户返回。

search.Filter = "(&(objectClass=user))";

我尝试了许多 OU 和 DC 的变体,但没有任何结果。

 string DomainPath = "LDAP://hs.domain.org";
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                //The following filter does work
                //search.Filter = "(&(objectClass=user))";

                search.Filter = string.Format("(&(objectClass=user)(OU=IT Users,OU=HSD Users,DC=hs,DC=domain,DC=org)");
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");//first name
                search.PropertiesToLoad.Add("manager");


                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)

标签: c#ldap

解决方案


您使用的 LDAP 过滤器无效,因此不返回任何记录。要在特定容器/OU 或子树中定位对象,您需要将 searchRoot 设置为路径。

要查找直接包含在特定容器/OU 中的所有条目,请使用以下构造函数将 SearchScope 设置为 1 (OneLevel)

DirectorySearcher(DirectoryEntry, String, String[], SearchScope)

如果要查找特定容器/OU的所有匹配条目,则可以使用上面的构造函数,但使用特定容器/OU 作为 searchRoot。


推荐阅读