StackTrace
StackTrace

Reputation: 9416

Fastest way of reading a property from LDAP/Active Directory Search results

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 = "([email protected])";
        SearchResult adSearchResult = adSearch.FindOne();
    }
}

From the sample above, what is the most effecient way of retrieving the property "givenname" and storing it into a string variable?

Upvotes: 0

Views: 867

Answers (1)

marc_s
marc_s

Reputation: 754598

Since you have the property in the list of properties to load in the search, just access that property in the search result:

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 = "([email protected])";

        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();
            }
        }
    }
}

Upvotes: 2

Related Questions