Click here to Skip to main content
15,884,472 members
Articles / Programming Languages / C#
Tip/Trick

Get List of Active Directory Users in C#

Rate me:
Please Sign up or sign in to vote.
4.76/5 (27 votes)
30 May 2013CPOL1 min read 319.2K   41   15
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:

C#
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.

C#
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionEnabled or SurName property didn't get it Pin
Member 1521742126-May-21 4:45
Member 1521742126-May-21 4:45 
QuestionSame code not working in IIS server Pin
Member 110526809-Dec-19 1:35
Member 110526809-Dec-19 1:35 
Questionineffecient to use (&(objectClass=user)(objectCategory=person)) as filter Pin
alekcarlsen23-Mar-15 22:00
alekcarlsen23-Mar-15 22:00 
QuestionSome issues in the code Pin
Member 113800762-Feb-15 8:33
Member 113800762-Feb-15 8:33 
GeneralMy vote of 5 Pin
z_smahi9-Dec-14 21:27
z_smahi9-Dec-14 21:27 
GeneralMy vote of 5 Pin
Anurag Gandhi7-Dec-14 2:26
professionalAnurag Gandhi7-Dec-14 2:26 
SuggestionWorks great Pin
Denver802115-Nov-14 7:02
Denver802115-Nov-14 7:02 
QuestionNice Article Thanks Pin
PiyushMCA8-Oct-14 2:05
PiyushMCA8-Oct-14 2:05 
AnswerRe: Nice Article Thanks Pin
Naufel Basheer8-Oct-14 21:01
Naufel Basheer8-Oct-14 21:01 
QuestionThis code works fine on my local not on web server. Pin
Member 253705116-May-14 9:13
Member 253705116-May-14 9:13 
AnswerRe: This code works fine on my local not on web server. Pin
Naufel Basheer26-Jun-14 23:33
Naufel Basheer26-Jun-14 23:33 
SuggestionWhy Do It Like This? Pin
three_sixteen31-Jul-13 7:47
three_sixteen31-Jul-13 7:47 
QuestionNaming is misleading Pin
jim lahey30-May-13 1:39
jim lahey30-May-13 1:39 
Suggestionimproved for use within current domain instead of hardcoded string Pin
BigTimber@home29-May-13 10:28
professionalBigTimber@home29-May-13 10:28 
GeneralRe: improved for use within current domain instead of hardcoded string Pin
newton.saber30-May-13 7:45
newton.saber30-May-13 7:45 
Took your sample, pasted it into LinqPad*, added a ref to the System.DirectoryServices.dll and ran it. Worked amazingly well. Thanks.

Learn more about LinqPad* and download it at: http://www.linqpad.net/

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.