Hi all,

I'm new to C# and I'm trying to write an function that query AD to check if an e-mailaddress already exists. If the address is found it return false, and if it's available/unique, it returns true. Not sure of the syntax, but this is what I've got so far.

public bool checkIfUniqueInAD(string checkattribute, string userName, string passWord, string AdsiPath)
using (DirectoryEntry de = new DirectoryEntry())

// List off the properties we wish to retrieve
//String[] propertyNames = new String[] { "canonicalName", "distinguishedName", "givenName", "sn", "sAMAccountName", "userAccountControl", "lastLogonTimestamp" };
String[] propertyNames = new String[] { checkattribute };
// connect to the selected directory path and
// set credentials to run the query.
de.Path = AdsiPath; // In format "LDAP://servername/DC=yourdomain,DC=com"
de.AuthenticationType = AuthenticationTypes.Secure;
de.Username = userName; // In format "domain\user"
de.Password = passWord; // In format "password"

// create a directory searcher which we wrap around the
// directory object we want to search
using (DirectorySearcher searcher = new DirectorySearcher(de))
searcher.SearchRoot = de;
searcher.Filter = "(&(objectCategory=user))";
searcher.SearchScope = SearchScope.Subtree;

// Load the desired attributes and perform the query
searcher.PropertiesToLoad.AddRange( propertyNames );
SearchResultCollection searchResult = searcher.FindAll();

if (searchResult ==null)
return true; // No match found. Value is unique
return false; // Value is not unique. We'll have to try with a new one

} // Catch any exception accessing the directory object
catch (Exception ex)
throw new UnexpectedDataException("Unable to verify uniqueness with Active Directory. Cause: Unable to connect to AD");
// Close the directory object

Does this syntax seem to be correct? Any suggestions of improvements?

I was thinking maybe to be able to have retries if the first try is unable to connect to the server. Any thoughts of how to implement that?