views:

56

answers:

1

It seems to me that one should always properly dispose resources when calling Directory Services API with no exception (yet many samples, blogs and tutorials often ignore, or do one way with this call, and the other way with another call). Since all of the following DS classes implement the Dispose method, so I just want to confirm once and for all:

using (DirectoryEntry dirEntry = new DirectoryEntry()) 
{
    using (DirectorySearcher dirSearcher = new DirectorySearcher())
    {
        dirSearcher.SearchRoot = dirEntry;
        dirSearcher.Filter = ...;
        using (SearchResultCollection src = dirSearcher.FindAll())
        {
            //Other code that deals with result
        } 
    }
}

should always be done. Am I running into any risk by always systematically and religiously doing the above?

+6  A: 

It's actually very important to dispose Directory Services objects - many of them wrap COM+ resources and you will cause resource leaks if you fail to dispose.

So yes, you're doing the right thing, definitely, and no, there's no risk when you wrap them in using.

Aaronaught