DirectorySearcherfilter

当我运行此查询时

// Next row is used to login to AD DirectoryEntry entry = GetEntry(domain, adminUser, adminPassword); // Here starts the query DirectorySearcher search = new DirectorySearcher(entry) { SearchScope = SearchScope.Subtree, Filter = "(&" + "(objectClass=user)" + // "(distinguishedname=*OU=Ingegneria*)" + "(givenname=s*)" + "(samaccountname=*100)" + ")" }; search.PropertiesToLoad.Add("distinguishedname"); SearchResultCollection result = search.FindAll(); 

我得到六个条目,这是正确的。
所有记录,如果我使用record.GetDirectoryEntry()都有

 distinguishedname: CN=xxx,OU=Utenti,OU=Ingegneria,DC=xxx,DC=xxx 

无论如何,如果我删除filter的distinguishedname部分的评论,我得到零条目!
我也尝试使用search.PropertiesToLoad.Add("distinguishedname"); 没有运气。
如何在filter中搜索distinguishedname

更新:
如果我尝试在filter中使用"(distinguishedname=*)" + ,我仍然会得到六条记录,所以我想我可以在distinguishedname上搜索…
UPDATE2:
我还尝试使用搜索Active Directory中的代码为OU使用OU的部分路径 :

 Filter = "(&(objectClass=user)(ou=Ingegneria))"; 

但我没有条目(如果我删除(objectClass=user)部分我有两个)

如果您只想查询,那么您应该在初始连接中绑定到该容器:

 // Next row is used to login to AD string ldapPath = "LDAP://OU=Ingegneria,DC=xxx,DC=xxx"; DirectoryEntry searchRoot = GetEntry(ldapPath, adminUser, adminPassword); // Here starts the query DirectorySearcher search = new DirectorySearcher(searchRoot) { SearchScope = SearchScope.Subtree, Filter = "(&" + "(objectClass=user)" + "(givenname=s*)" + "(samaccountname=*100)" + ")" }; search.PropertiesToLoad.Add("distinguishedname"); SearchResultCollection result = search.FindAll(); 

这样,您还可以大量减少AD中需要搜索的空间,从而加快搜索速度。

如果您使用的是.NET 3.5或更高版本,则可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

 // create your domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Ingegneria,DC=xxx,DC=xxx"); // define a "query-by-example" principal - here, we search for a UserPrincipal UserPrincipal qbeUser = new UserPrincipal(ctx); qbeUser.GivenName = "s*"; qbeUser.SamAccountName = "*100"; // create your principal searcher passing in the QBE principal PrincipalSearcher srch = new PrincipalSearcher(qbeUser); // find all matches foreach(var found in srch.FindAll()) { // do whatever here - "found" is of type "Principal" UserPrincipal userFound = found as UserPrincipal; if(userFound != null) { // do something with your user principal here.... } } 

如果您还没有 – 绝对阅读MSDN文章.NET Framework 3.5中的管理目录安全主体,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新function