Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Access Active Directory - The .NET Way

2.67/5 (18 votes)
7 Jun 2007CPOL 1  
Accessing Active Directory

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:

C#
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;
}

History

  • 7th June, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)