Saturday, September 16, 2006

Working with Directory Services using .Net

DirectoryEntry and DirectorySearcher are major classes and most of time only these two are needed to work with Directory Service. Use following steps to retrieve user list from Directory Service
  • Use DirectoryEntry and bind using a query. Domain user’s credential is required only when user account running this query is not a domain user.
    DirectoryEntry root = new DirectoryEntry("LDAP://<domainName>/CN=Users,DC=<DomainName>", "<DomainName>\\<domainUser>", "<Password>");
  • Create DirectorySearcher and pass the DirectoryEntry earlier binded to this object. We need this so that we can use a filter to get only users and not groups.
    DirectorySearcher searcher = new DirectorySearcher(root);
  • Set a filter.
    searcher.Filter = "(objectClass=user)";
  • Fire a query.
    SearchResultCollection userList = searcher.FindAll();
  • Retrive the user information from the result collection.
    foreach (SearchResult result in userList)
    {
    DirectoryEntry userEntry = result.GetDirectoryEntry();
    string loginID = (string)userEntry.InvokeGet("samAccountName");
    string userName = (string)userEntry.InvokeGet("displayName");
    string emailID = (string)userEntry.InvokeGet("mail");

    }

No comments: