web analytics

Dispose your Directory Services objects

Options

codeling 1599 - 6654
@2019-11-19 13:46:57

You may 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 this:

 

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

            }

        }

    }

}

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com