当我运行此查询时
// 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
无论如何,如果我删除对distinguishedname
部分过滤器的评论,我会收到零条目!!
我还试图使用search.PropertiesToLoad.Add("distinguishedname");
但没有运气
如何在过滤器中搜索distinguishedname
?
更新
如果我尝试在过滤器中使用"(distinguishedname=*)" +
,我仍然会得到六条记录,所以我想我可以搜索distinguishedname ...
的 UPDATE2:
我还尝试使用Search Active Directory for an OU using a partial path to the OU中的代码:
Filter = "(&(objectClass=user)(ou=Ingegneria))";
但我没有条目(如果删除(objectClass=user)
部分,我有两个)
答案 0 :(得分:28)
如果您只想查询,那么您应该在初始连接中绑定到该容器:
// 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文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement