首页 > 解决方案 > DirectorySearcher:如何仅获取“真实”用户的条目

问题描述

我使用 aDirectorySearcher从 Active Directory 中获取所有用户 - 但我只需要获取“真实”用户。

筛选:

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

但我得到了所有用户帐户,例如:

henry.miller            <-wanted
ernest.hemingway        <-wanted
HealthMailboxced7671    <-not wanted 

问题:如何修改我的过滤器以仅返回真实用户?

我的整个代码:

string DomainPath = "LDAP://DC=writers,DC=local";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname");

SearchResult result;

SearchResultCollection resultCol = search.FindAll();

if (resultCol != null)
{
    for (int counter = 0; counter < resultCol.Count; counter++)
    {
        result = resultCol[counter];

        if (result.Properties.Contains("samaccountname"))
        {
            Console.WriteLine((String)result.Properties["samaccountname"][0]);
        }
    }
}

标签: c#.netactive-directoryuser-accountsdirectorysearcher

解决方案


在下面尝试使用 LDAP

 (&(objectCategory=person)(objectClass=user)(sAMAccountName=*)(!(cn=*O*)))

仅供参考 - CN 是通用名称。您可以在此处获取有关 LDAP 的更多信息

您还问我可以用什么属性检索 cn。在这里,您可以通过此代码片段提取(用于双重检查)。但据我所知,它只是 CN

 foreach (string property in result.Properties.PropertyNames)
{
      foreach (Object propertyValue in result.Properties[property])
     {
        // print out the Property Value here
      }
}

推荐阅读