Dispose your Directory Services objects Options

codeling Posts: 1153 Points: 4845
Posted: Tuesday, November 19, 2019 1:46:57 PM

Use a DirectorySearcher object to search and perform queries against an Active Directory Domain Services hierarchy using Lightweight Directory Access Protocol (LDAP). LDAP is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports directory searching. 

Due to implementation restrictions, the SearchResultCollection class cannot release all of its unmanaged resources when it is garbage collected. To prevent a memory leak, you must call the Dispose method when the SearchResultCollection object is no longer needed.

Taking into account both of the above points, your code might look something like:

 

using (DirectoryEntry rootEntry =

    new DirectoryEntry(ADCreds.Ldap, ADCreds.Username, ADCreds.Password))

{

    using (DirectorySearcher DirSearch = new DirectorySearcher(rootEntry, filter))

    {

        DirSearch.PageSize = 1000; // or some suitable value > 0

        using (SearchResultCollection SearchResult = DirSearch.FindAll())

        {

            foreach (SearchResult SearchRes in SearchResult)

            {

                // do something

            }

        }

    }

}

 

 
Users browsing this topic
Guest