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
- using System.DirectoryServices;
- 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
- public class ClsUsers
- {
- public string AccountName { get; set; }
- public string DisplayName { get; set; }
- }
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.
- private void GetADUsers()
- {
- dt.Columns.AddRange(new DataColumn[2]
- {
- new DataColumn("AccountName", typeof (string)),
- new DataColumn("GivenName", typeof (string))
- });
- using(var context = new PrincipalContext(ContextType.Domain, "enter your domain here"))
- {
- using(var searcher = new PrincipalSearcher(new UserPrincipal(context)))
- {
- foreach(var result in searcher.FindAll())
- {
- DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
- var clsuser = new ClsUsers();
- dt.Rows.Add(Convert.ToString(de.Properties["samAccountName"].Value), Convert.ToString(de.Properties["givenName"].Value));
- }
- GridView1.DataSource = dt;
- GridView1.DataBind();
- }
- }
- }
Output
Closure
That's how we can fetch the Active Directory entries of user. Hope you find this helpful.
Happy coding!