Access Active Directory – The .NET Way

Introduction

Accessing Active Director (AD) is one of the most basic scenarios for an Intranet application. For a new developer though, sometimes it becomes clumsy to get this. But believe me, it is just as simple as hitting a full toss (shows how much I love cricket).

Using the Code

The following code shows how to do it with C#. Remember to include System.DirectoryServices. Here you go:


public static Hashtable SearchLDAP(string userID)
{
    DirectoryEntry entry = new DirectoryEntry("LDAP://DC=Domain,DC=com");
    DirectorySearcher mySearcher = new DirectorySearcher(entry);
    mySearcher.Filter = "(&(objectClass=user)(anr="+ userID +"))";

    mySearcher.PropertiesToLoad.Add("givenname");
    mySearcher.PropertiesToLoad.Add("sn");
    mySearcher.PropertiesToLoad.Add("mail");
    mySearcher.PropertiesToLoad.Add("description");
    mySearcher.PropertiesToLoad.Add("l");

    Hashtable associateDetailsTable = new Hashtable();
    ResultPropertyValueCollection resultCollection;
    SearchResult searchResult = mySearcher.FindOne();

    associateDetailsTable.Add("AssociateID", userID);
    if(searchResult != null)
    {
    resultCollection = searchResult.Properties["givenname"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("FirstName", result.ToString());
    }
    resultCollection = searchResult.Properties["sn"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("LastName", result.ToString());
    }
    resultCollection = searchResult.Properties["mail"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("Mail", result.ToString());
    }
    resultCollection = searchResult.Properties["description"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("Designation", result.ToString());
    }
    resultCollection = searchResult.Properties["l"];
    foreach(object result in resultCollection)
    {
    associateDetailsTable.Add("Location", result.ToString());
    }
    }
    return associateDetailsTable;
}