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;

using System.DirectoryServices.AccountManagement

Classes

PrincipalContext

DiectoryEntry

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 { get; set; }
  4. public string DisplayName { get; set; }
  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!