[c#] Connect to Active Directory via LDAP

I want to connect to our local Active Directory with C#.

I've found this good documentation.

But I really don't get how to connect via LDAP.

Can somebody of you explain how to use the asked parameters?

Sample Code:

  static DirectoryEntry createDirectoryEntry()  
  {  
     // create and return new LDAP connection with desired settings  

     DirectoryEntry ldapConnection     = new DirectoryEntry("rizzo.leeds-art.ac.uk");  
     ldapConnection.Path               = "LDAP://OU=staffusers,DC=leeds-art,DC=ac,DC=uk";  
     ldapConnection.AuthenticationType = AuthenticationTypes.Secure;  
     return ldapConnection;  
  }  

I just have the Hostname and the IP Address of our Active Directory Server. What does DC=xxx,DC=xx and so on mean?

This question is related to c# active-directory

The answer is


If your email address is '[email protected]', try changing the createDirectoryEntry() as below.

XYZ is an optional parameter if it exists in mydomain directory

static DirectoryEntry createDirectoryEntry()
{
    // create and return new LDAP connection with desired settings
    DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
    ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
    ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
    return ldapConnection;
}

This will basically check for com -> mydomain -> XYZ -> Users -> abcd

The main function looks as below:

try
{
    username = "Firstname LastName"
    DirectoryEntry myLdapConnection = createDirectoryEntry();
    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
    search.Filter = "(cn=" + username + ")";
    ....    

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP