Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get List of Active Directory Users in C#

0.00/5 (No votes)
30 May 2013 1  
List AD users using DirectoryServices (System.DirectoryServices)

Introduction

This tip describes how to list Active Directory users.

Using the Code

The below code demonstrates how can we fetch Active Directory (AD) using Directory Service. For this, I'm using object array (Users) and here is the structure:

public class Users
{
    public string Email { get; set; }
    public string UserName { get; set; }
    public string DisplayName { get; set; }
    public bool isMapped { get; set; }
}

The code below shows how to fetch user information from Active Directory.

public List<Users> GetADUsers()
{
    try
    {
        List<Users> lstADUsers = new List<Users>();
        string DomainPath = "LDAP://DC=xxxx,DC=com"
        DirectoryEntry searchRoot = new DirectoryEntry(DomainPath); 
        DirectorySearcher search = new DirectorySearcher(searchRoot);
        search.Filter = "(&(objectClass=user)(objectCategory=person))";
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertiesToLoad.Add("mail");
        search.PropertiesToLoad.Add("usergroup");
        search.PropertiesToLoad.Add("displayname");//first name
        SearchResult result;
        SearchResultCollection resultCol = search.FindAll();
        if (resultCol != null)
        {
            for (int counter = 0; counter < resultCol.Count; counter++)
            {
                string UserNameEmailString = string.Empty;
                result = resultCol[counter];
                if (result.Properties.Contains("samaccountname") && 
                         result.Properties.Contains("mail") && 
                    result.Properties.Contains("displayname"))
                {
                    Users objSurveyUsers = new Users();
                    objSurveyUsers.Email = (String)result.Properties["mail"][0] + 
                      "^" + (String)result.Properties["displayname"][0];
                    objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                    objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                    lstADUsers.Add(objSurveyUsers);
                }
            }
        }
        return lstADUsers;
    }
    catch (Exception ex)
    {

}

Let's see what is happening here...

The DirectoryEntry class encapsulates an object in Active Directory Domain Services, DirectoryEntry(DomainPath) initializes a new instance of the class that binds this instance to the node in Active Directory Domain Services located at the specified path, i.e., DomainPath.

In DirectorySearcher, create a DirectorySearcher object which searches for all users in a domain. search.Filter = "(&(objectClass=user)(objectCategory=person))" filters the search.

The search filter syntax looks a bit complicated, but basically it filters the search results to only include users - "objectCategory=person" and "objectClass=user" - and excludes disabled user accounts by performing a bitwise AND of the userAccountControl flags and the "account disabled" flag.

Note: SAMAccountName is unique and also indexed. sAMAccountName must be unique among all security principal objects within the domain.

search.FindAll(); retrieves all the elements that match the conditions defined.

Let's see how we get the current login user.

public string GetCurrentUser()
{
    try
    {
        string userName = HttpContext.Current.User.Identity.Name.Split('\\')[1].ToString();
        string displayName = GetAllADUsers().Where(x => 
          x.UserName == userName).Select(x => x.DisplayName).First();
        return displayName;
    }
    catch (Exception ex)
    { //Exception logic here 
    }
}

Let's see what this code snippet does:

  • HttpContext.Current.User.Identity returns the Windows identity object including AuthenticationType ("ntml", "kerberos" etc..), IsAuthenticated, Name ("Domain/username").
  • HttpContext.Current.User.Identity.Name returns "Domain\\username" .

Hope this helps you understand how directory service works with AD.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here