DirectoryEntry Object Clean-up 

Tags:

In my previous post I discussed a COMException that was getting thrown when I attempted a DirectoryEntry.Invoke("SetPassword", password). While developing the work around to just catch any exception thrown by this object MS requested a copy of our code because we had the unfortunate ability to reproduce the error very consistently. After reviewing our code and the code workaround MS provided some very important feedback about properly cleaning up the DirectoryEntry object.

   

We had initially been using a "using" block

   

using(DirectoryEntry dirEntry = new DirectoryEntry(…))

{

}

   

However, the Dispose method, as pointed out by Microsoft, that is used is really the Component.Dispose() method. The Component's Dispose method does not close the DirectoryEntry object's connection with the LDAP/Active Directory Server, thus as you go along creating more and more DirectoryEntry objects you are opening more and more connections and never returning them. Microsoft's recommendation is to use the try/catch/finally block as shown.

   

DirectoryEntry dirEntry = null;

try

{

dirEntry = new DirectoryEntry(…);

}

//catch not required

catch(Exception ex)

{

//log exception

}

finally

{

if(dirEntry != null)

{

dirEntry.Close();

dirEntry.Dispose();

}

}

 
Posted by David McWee on 13-May-08
0 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
 
Name:
URL:
Email:
Comments: