Getting Users From Active Directory

Before moving on let's understand some assemblies and classes associated with Active Directory which are used to perform some operations related to Active Directory.

Assemblies

using System.DirectoryServices;

  • This namespace provides easy access to Active directory.
using System.DirectoryServices.AccountManagement
  • This namespace basically used to manipulate users,computers and security groups across the multiple directory services say Active Directory Domain Services(AD DS) and Active Directory Lightweight Directory Services(AD LDS) and also provide the access to users, computers and security groups. 

Classes

PrincipalContext

  • This class basically wrap server or domain, container and credentials against all operations. 

DiectoryEntry

  • This class is used to access the entries from schema entries, also let us fetch entries (attribute values) and update the same .
Let us perform activity of fetching Active Directory users. 

We have to use above assemblies for accessing and performing operation against Active Directory.

Add the following assemblies 

  1. using System.DirectoryServices;  
  2. using System.DirectoryServices.AccountManagement;  
Let us say we are going to fetch couples of Active Directory Entries like givenName and samAccountName of the user object. 

Let's add the following class ClsUser with properties

  1. public class ClsUsers  
  2. {  
  3.    public string AccountName { getset; }  
  4.    public string DisplayName { getset; }  
  5. }  
Now we are going to fetch these entries using the following code and display the same in a grid using the following piece of code. 
  1. private void GetADUsers()  
  2. {  
  3.     dt.Columns.AddRange(new DataColumn[2]  
  4.     {  
  5.         new DataColumn("AccountName"typeof (string)),  
  6.             new DataColumn("GivenName"typeof (string))  
  7.     });  
  8.     using(var context = new PrincipalContext(ContextType.Domain, "enter your domain here"))  
  9.     {  
  10.         using(var searcher = new PrincipalSearcher(new UserPrincipal(context)))  
  11.         {  
  12.             foreach(var result in searcher.FindAll())  
  13.             {  
  14.                 DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;  
  15.                 var clsuser = new ClsUsers();  
  16.                 dt.Rows.Add(Convert.ToString(de.Properties["samAccountName"].Value), Convert.ToString(de.Properties["givenName"].Value));  
  17.             }  
  18.             GridView1.DataSource = dt;  
  19.             GridView1.DataBind();  
  20.         }  
  21.     }  
  22. }  

Output



Closure

That's how we can fetch the Active Directory entries of user. Hope you find this helpful.

Happy coding!

Up Next
    Ebook Download
    View all
    Learn
    View all