Querying Active Directory using CSharp (C#)

Article describes “Querying Active Directory using CSharp (C#)” via LDAP Service. I have developed a sample application around this topic with following goals, download source code and try it out yourself.

  • Retrieve User Details or an Object from AD based on Username – sAMAccountName
  • Retrieve User Details or an Object from AD based on Email ID – mail

Querying Active Directory using csharp

 

Tips: with help of filter you can apply all the attributes/properties supported by Microsoft – Windows Active Directory.  All you have to do is change an attribute in the filter according to your needs.


Video Tutorial by Webucator

Thanks to Webucator.com making this wonderful video tutorial for this article. Webucator provides various C# online training classes by Microsoft Certified Instructors.


Required Details

Following details required to retrieve any information from Active Directory and it’s required for sample application too.

  • LDAP address (For e.g.: mydomain.com or IP of the Domain Controller/Global Catalog[GC])
  • Port # (For e.g.: 3289 or 389) where would you to like search?
  • Domain Username
  • Domain Password

Reference: will introduce you to the classes needed for querying Active Directory using CSharp (C#). Have a look and know more about it.


How to do – Step by Step approach

For an easy understanding, we are going to follow step by step approach. Experts can combine the few steps into single line of code or as you see fit.

Step 1

Compose LDAP address (you can use IP address too), create DirectoryEntry object using composed ldapAddress, username and password

// Creating a directory entry object by passing LDAP address

string ldapAddress = "LDAP://mydomain.com:3289";
DirectoryEntry de = new DirectoryEntry(ldapAddress, username, password);

Step 2

Create DirectorySearcher object using DirectoryEntry object we created from Step 1.

DirectorySearcher ds = new DirectorySearcher(de);

Step 3

Create an Filter and apply that filter in the DirectorySearcher object. Below you will find two filters to perform different needs.  To know more about Filter Syntax click here.

Filter based on Username – sAMAccountName

ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname="+ username + "))";

Filter based on Email ID – mail

ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(mail=" + email + "))";

Step 4

Apply the SearchScope in the DirectorySearcher object.

ds.SearchScope = SearchScope.Subtree;

Step 5

Use an API from DirectorySearcher class; choose according to your need and storing the result object using SearchResult class object. This example using FindOne API, it returns object found at first during search.

SearchResult rs = ds.FindOne();

Step 6

Retrieving an attribute value from SearchResult object (default  Attribute List ), so you can retrieve appropriate one according to your requirement. Few attributes used below as an example.

// Accessing few attributes like- 
// samaccountname => Username
// givenName => First Name
// sn => Last Name
// mail => Email Id

if (rs.GetDirectoryEntry().Properties["samaccountname"].Value != null)
    lblUsernameDisplay.Text = "Username : " + rs.GetDirectoryEntry().Properties["samaccountname"].Value.ToString();

if (rs.GetDirectoryEntry().Properties["givenName"].Value != null)
    lblFirstname.Text = "First Name : " +rs.GetDirectoryEntry().Properties["givenName"].Value.ToString();

if (rs.GetDirectoryEntry().Properties["sn"].Value != null)
    lblLastName.Text = "Last Name : " + rs.GetDirectoryEntry().Properties["sn"].Value.ToString();

if (rs.GetDirectoryEntry().Properties["mail"].Value != null)
    lblEmailId.Text = "Email ID : " + rs.GetDirectoryEntry().Properties["mail"].Value.ToString();

Accessing User Certificate from Active Directory

DirectoryEntry de = rs.GetDirectoryEntry();

Byte[] certificateBytes = de.Properties["userCertificate"].Value as byte[];
X509Certificate2 cert = new X509Certificate2(certificateBytes);

Once you have Certificate object, do as your requirement. Just a start point like

DateTime dateAfter = cert.NotAfter;

DateTime dateBefore = cert.NotBefore;

Note: I have added code snippet here, this certificate access is not part of downloadable source code :)


Source Code

As we discussed step by step approach to retrieve user details or an object from Active Directory.  Complete source code present in GitHub also downloadable archive below.

  Download – ActiveDirectory.zip

Beginning of yours

Now, you have learned “Querying Active Directory using CSharp (C#)” and how to interact with ActiveDirectory to do retrieving/search user. Have fun and make use of provided source code from article.

Happy learning!