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

Step 2

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

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

Filter based on Email ID - mail

Step 4

Apply the SearchScope in the DirectorySearcher object.

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.

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 User Certificate from Active Directory

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

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!

  • pit

    Nice article exacly what i searching thx

  • Ajay

    Simple and best…Thanx

  • Ajay

    I am updating AD flag(Password never expires) …but No luck…My application runs without error.Please help me

    if (rs.GetDirectoryEntry().Properties[“userAccountControl”].Value != null) {

    s = (int)rs.GetDirectoryEntry().Properties[“userAccountControl”].Value;

    rs.GetDirectoryEntry().Properties[“userAccountControl”].Value = 65536;




    • Jeevanandam Madanagopal

      Hello Ajay – I believe you’re trying to set user account as password never expire flag, please try this.

      DirectoryEntry userObj = rs.GetDirectoryEntry();
      s = (int)userObj.Properties[“userAccountControl”].Value;
      userObj.Properties[“userAccountControl”].Value = s | 0x10000;

      List of property flags, take a look http://support.microsoft.com/kb/305144


  • ManjunathNaik

    I tried the above code, but i am getting “server is not operational ” error. 
    Can you please the help me why it showing this error.

    • jeevatkm

      @ManjunathNaik Typically you get this error in following scenarios
      1. if System.DirectoryServices can’t contact the server.  So verify the following items:
      – Verify the port you’re connecting is open or not (389 or 3289)
      – Verify the DNS name; provide fully qualified DNS or if you’re not sure provide IP of the LDAP server
      – Still if you’re facing issue, may be firewall issues. Check with network admin
      2. Continues access of Tokengroups, GUID,… in a loop; refreshing Cache will do the trick.

  • Roshan Mehta

    Just letting you know you have a typo when initializing the DirectorySearcher. The parameter passed into the constructor should be de, not ds.

    • jeevatkm

      @Roshan Mehta Thank you, article updated :)

  • Murali

    I am a new learner of script, want to know how to use in AD. Eager to learn

    please guide with simple documents to read and start working with basis script in AD and gradually advancing in order.

    Thanking you


  • Murali

    what scripting (Javascript, Perl, c#, c++) should I learn to work on Active directory scriptings..

    thanks again,


    • Hello Murali – Good to hear about your learning interest!
      Active Directory Services can accessed and manipulated in major programming languages capable of LDAP functions. Current article provides start up for accessing Active Directory using C#.

      So choose your comfortable programing language C#, Java, PHP, Perl for your need.


  • Sarvesh Chaudhary

    Nice article what i am exactly looking for.


  • abdullah


    but i need how i can edite user information??

    please help me

    • Hello Abdullah – It’s easy to update. Let me describe.

      Once you have search result object SearchResult rs = ds.FindOne();, you will be able to access/update user information.

      For example: updating ‘givenName’

      rs.GetDirectoryEntry().Properties["givenName"].Value = "New value here";




  • YK

    Code doesn’t reset the User information fields. When querying a second time, if some of the fields for the second user are not set in the AD, the form displays information from the first user (query).

    • Hello YK – I will check the issue you have describe in the comment and let you know.


  • george

    Nice written article , exactly what i was looking for. Thanks :)

  • fabrizio esposito

    Hi Jeeva,

    first of all thank’s for sharing your code.

    Starting from your code i made some modification on it but get in trouble and maybe u could help find out the reason why and the solution.

    I’ve add the thumbnailphoto attribute and render, if not null, into picture box (and it works fine), also introduced the possibility to download locally the picture and to browse computer folder and upload photo on AD.

    the last point is the issue, I tryed to insert the byte array without success but the strange is that i have no exception or other from the code.

    making the same (update) on mobile phone field for example is quite the same result, no error, no exception but no update made…..

    here the way used to update “mobile” :

    rs.GetDirectoryEntry().Properties[“mobile”].Value = “123456”;

    any suggestion will be very appreciate.


    • Hello Fabrizio – as per your code snippet, please check the user you’re using for AD object modification for write permission.


  • sabirahmed

    int s = (int)Detry.Properties[“userAccountControl”].Value;

    Detry.Properties[“userAccountControl”].Value = s | 0x10000;

    while using this it shows “object reference not set to instance of an object” error shows

    help me



  • Sure, please share your function code snippet to jeeva at myjeeva dot com


  • Felipe Gomes Machado

    Hi Jeevanandam M, great article…
    I have a question, and if I need what the connection to be secure, it’s possible?
    My connection needs SSL.