I'm working with System.DirectoryServices and I have the following method that I use to create the DirectoryEntry:
static DirectoryEntry CreateDirectoryEntry(string connectionPath) { DirectoryEntry ldapConnection = null; try { ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME)) ldapConnection.Path = connectionPath; ldapConnection.AuthenticationType = AuthenticationTypes.Secure; } catch (Exception ex) { MessageBox.Show("Exception Caught in createDirectoryEntry():\n\n" + ex.ToString()); } return ldapConnection; } This method is called in this manner:
DirectoryEntry ldapConnection = CreateDirectoryEntry("LDAP://OU=Example,DC=domain,DC=com"); I read that it is best practice to use a using statement for anything that implements IDisposable. My question is, do I need a using statement just in the CreateDirectoryEntry() method or should I also do it for each call?
To illustrate what I mean, is this sufficient?:
static DirectoryEntry CreateDirectoryEntry(string connectionPath) { DirectoryEntry ldapConnection = null; try { using (ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME)) { ldapConnection.Path = connectionPath; ldapConnection.AuthenticationType = AuthenticationTypes.Secure; } } catch (Exception ex) { MessageBox.Show("Exception Caught in createDirectoryEntry():\n\n" + ex.ToString()); } return ldapConnection; } Or would I also need to use a using statement on the call like this?:
using (DirectoryEntry ldapConnection = CreateDirectoryEntry("LDAP://OU=Example,DC=domain,DC=com")) { //Do something with ldapConnection } Any help is greatly appreciated!
Note: I can't use System.DirectoryServices.AccountManagement for this solution so please keep answers related to System.DirectoryServices. Thanks!