Monday, October 4, 2010

C# code to query LDAP directory and Active Directory

To query LDAP or AD server with out the domain in the path, see the following code:

public List GetAllUsers(string query)
        {
            var users = new List();
            //ldapServer does not contain the domain i.e. server.company.com 
            using (var dir = new DirectoryEntry(ldapServer, ldapUser, ldapPassword,
                      AuthenticationTypes.ServerBind))
            {
                using (var search = new DirectorySearcher(dir))
                {
                    search.Filter = query;
                    SearchResultCollection resultCol = search.FindAll(); 
                    foreach (SearchResult userProfile in resultCol)
                    {
                        LdapUser user = PopulateUserObject(userProfile);
                        users.Add(user);
                    }
                }
            }
            return users;
        }

To query LDAP or AD server domain, see the following code:

var dir = new DirectoryEntry(adPath, adUser, adPassword)
     { // ad path contains the domain i.e. DC=TEST,DC=Your_COMPANY,DC=COM   
      using (var search = new DirectorySearcher(dir))
      {
       search.Filter = query;
       SearchResultCollection resultCol = search.FindAll(); 
       foreach (SearchResult userProfile in resultCol)
       {
           LdapUser user = PopulateUserObject(userProfile);
           users.Add(user);
       }
      }                                     
      };

To learn more about AuthenticationTypes (part of System.DirectoryServices.dll), go to http://msdn.microsoft.com/en-us/library/system.directoryservices.authenticationtypes.aspx

No comments:

Post a Comment