Showing posts with label Active DIrectory User List. Show all posts
Showing posts with label Active DIrectory User List. Show all posts

Tuesday, November 5, 2013

Listing All Users in AD C# & ASP.Net

In a previous Post I described the code to get all the users in User Information List using Client Object Model.


In this post I will demonstrate listing all the AD users using C#. You need to add references to System.DirectoryServices and System.DirectoryServices.AccountManagement for this purpose.

Check the example below:

public class Example
{

   public List<ADUsers> ListAllADUsers()
        {
             List<ADUsers> users = new List<ADUsers>() ;


             using (var ctx= new PrincipalContext(ContextType.Domain, "your domain name"))
             {
                 using (var PSearcher= new PrincipalSearcher(new UserPrincipal(ctx)))
                 {
                     foreach (var account in PSearcher.FindAll())
                     {

                         string Name = Convert.ToString(account.DisplayName);
                         string SAMAccountName = Convert.ToString(account.SamAccountName);
                         string EmailAddress = Convert.ToString(account.UserPrincipalName);
                         users.Add(new ADUsers() { Name = Name, SAMAccountName=                                                                                      SAMAccountName, Email = EmailAddress });
                     }
                 }
             }
            return users;
        }
}
 public class ADUsers
    {
      
        public string Name { get; set; }        
        public string SAMAccountName { get; set; } 
        public string Email { get; set; }

    }

The method ListAllADUsers() returns the list of all the users in AD with Full Name, Domain Name and Email Address for each user.