Question

I currently have a couple methods here:

public ADHelper()
        {

           connection =  InitializeConnection();

        }

        private DirectoryEntry InitializeConnection()
        {
            DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://servername.domain.com:389/DC=domain,DC=com");
            ldapConnection.Username = "user"
            ldapConnection.Password = "password";

            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;

        }

I'd like to create another method to check and see if an object exists within that domain. I'm currently doing that with the following:

public bool Exists(string objectPath)
        {
            bool found = DirectoryEntry.Exists("LDAP://" + objectPath);
            return found;
        }

But that forces me to specify an entire LDAP string. I'd like to simply extend the initial ldapConnection with an OU and maybe CN parameter within the Exists() method. Is there any way to make this happen without making the Initialize() method public?

Thanks so much!

Was it helpful?

Solution

Maybe something like this:

public bool AccountExists(string userEmail)
{
    using (var root = GetLdapRoot())
    {
        using (var searcher = new DirectorySearcher(root))
        {
            searcher.Filter = string.Format("(&(objectClass=User)(mail={0}))", userEmail);
            searcher.PropertiesToLoad.Add("email");
            var result = searcher.FindAll();
            return result.Count > 0;
        }
    }
}


private static DirectoryEntry GetLdapRoot()
{
    return new DirectoryEntry("LDAP://DC=com"); //or whatever your root domain is. Set credentials if you need to
}

by setting a filter and being specific about what properties to load in, the search will be more efficient. By using the root as your LDAP:// string, you should be searching the entire directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top