views:

469

answers:

2

When using the DirectorySearcher in .net, are these two statements equal?

Same for both:

Dim ds As New DirectorySearcher
' code to setup the searcher

First statement

ds.FindOne()

Second statement

ds.SizeLimit = 1
ds.FindAll()

...except obviously that FindOne() returns a SearchResult object and FindAll() returns a SearchResultCollection object

+2  A: 

Yes, that would be almost the same.

Almost, because in .NET 2.0 (not sure if it's been fixed in more recent versions), the .FindOne() call had some issues with leaking memory, so best practice is (or was) to always use .FindAll() and iterate over your results.

Marc

marc_s
+2  A: 

@marc_s is right, except that the FindOne memory leak bug was in .NET 1.x and is fixed in .NET 2.0.

It happened because the .NET 1.x implementation of FindOne calls FindAll under the covers and does not always dispose the SearchResultCollection returned by FindAll:

public SearchResult FindOne()
{
    SearchResultCollection collection1 = this.FindAll(false);
    foreach (SearchResult result1 in collection1)
    {
       collection1.Dispose();
       return result1;
    }
    return null;
}

In the above code collection1.Dispose will not be called if the collection is empty (no result is found), resulting in a memory leak as described in the remarks section of the MSDN documentation for FindAll.

You can use FindOne safely in .NET 2.0. Or if you use FindAll, you need to make sure you dispose the returned SearchResultCollection or you will have the same memory leak, e.g.:

public SearchResult MyFindOne()
{
    using(SearchResultCollection results = this.FindAll(false))
    {
        if(results.Count > 0) return results[0];
        return null;
    }
}
Joe
Thanks for that extra info...very valuable!
davidsleeps