从LDAP / Active Directory搜索结果中读取属性的最快方法

时间:2014-03-27 09:00:13

标签: c# c#-4.0 active-directory ldap

using (DirectoryEntry rootEntry = new DirectoryEntry(ConfigurationKeys.Ldap, string.Empty, string.Empty, AuthenticationTypes.None))
{
    using (DirectorySearcher adSearch = new DirectorySearcher(rootEntry))
    {
        adSearch.SearchScope = SearchScope.Subtree;
        adSearch.PropertiesToLoad.Add("givenname");
        adSearch.PropertiesToLoad.Add("mail");

        adSearch.Filter = "(mail=myemail@mydomain.org)";
        SearchResult adSearchResult = adSearch.FindOne();
    }
}

从上面的示例中,检索属性的最有效方法是什么?给定名称"并将其存储到字符串变量中?

1 个答案:

答案 0 :(得分:2)

由于您要在搜索中加载属性列表中的属性,只需在搜索结果中访问该属性:

using (DirectoryEntry rootEntry = new DirectoryEntry(ConfigurationKeys.Ldap, string.Empty, string.Empty, AuthenticationTypes.None))
{
    using (DirectorySearcher adSearch = new DirectorySearcher(rootEntry))
    {
        adSearch.SearchScope = SearchScope.Subtree;
        adSearch.PropertiesToLoad.Add("givenname");
        adSearch.PropertiesToLoad.Add("mail");

        adSearch.Filter = "(mail=myemail@mydomain.org)";

        SearchResult adSearchResult = adSearch.FindOne();

        // make sure the adSearchResult is not null
        // and the "givenName" property is not null (could be empty / null)
        if(adSearchResult != null && adSearchResult.Properties["givenName"] != null) 
        {
            // make sure the givenName property contains at least one string value
            if (adSearchResult.Properties["givenName"].Count > 0)
            {
               string givenName = adSearchResult.Properties["givenName"][0].ToString();
            }
        }
    }
}