Click here to Skip to main content
Click here to Skip to main content

How to get User Data from the Active Directory

, 20 Apr 2004
Rate this:
Please Sign up or sign in to vote.
How to get User Data from the Active Directory using C#

Introduction

Last month the project manager asked me write to find all users information from the Active directory and which all fields are missing information for particular user. I was trying to search in Internet for information about .NET Active Directory examples, I could not able to find much information on the net, it prompted me write an article on this topic.

In this article, I will explain how to use Active Directory class and retrieve data from the component classes. You can cut and past below code lines and execute it but you need to pass domain name in Directory Entry constructor. Following example taken from one of my developed projects and modified for easy to understand.

I assumed that you have a general understanding of active directory before using this example.

Step 1:

Add System.DirectoryServices.Dll (from Project Add reference)

System.DirectoryServices provides easy access to active directory from managed code. This namespace contains two components classes, DirectoryEntry and DirectorySearcher.

Step 2:

Using System.DirectoryServices

Directory Entry Class: this class encapsulates a node or object in the active directory hierarchy. Use this class for binding to objects, reading properties and updating attributes.

Step 3:

DirectoryEntry entry = new DirectoryEntry("LDAP://DomainName");

Directory Searcher: It will perform queries against the active directory hierarchy

Step 4:

DirectorySearcher Dsearch = new DirectorySearcher(entry);

Step 5:

String Name="Richmond";

The Filter property supports for the all filter the information of the active directory.

// l = city name

Step 6:

dSearch.Filter = "(&(objectClass=user)(l=" + Name + "))";

Executes the search and returns a collection of the entries that are found.

Step 7:

This function checks active directory field is valid or not. Add this member function to you class.

Public static string GetProperty(SearchResult searchResult, 
 string PropertyName)
  {
   if(searchResult.Properties.Contains(PropertyName))
   {
    return searchResult.Properties[PropertyName][0].ToString() ;
   }
   else
   {
    return string.Empty;
   }
  }

Step 8:

// get all entries from the active directory.
// Last Name, name, initial, homepostaladdress, title, company etc..
 foreach(SearchResult sResultSet in dSearch.FindAll())
    {
          
     // Login Name
     Console.WriteLine(GetProperty(sResultSet,"cn"));
     // First Name
     Console.WriteLine(GetProperty(sResultSet,"givenName"));
     // Middle Initials
     Console.Write(GetProperty(sResultSet,"initials"));
     // Last Name
     Console.Write(GetProperty(sResultSet,"sn"));
     // Address
 string tempAddress=GetProperty(sResultSet,"homePostalAddress");

     if(tempAddress !=string.Empty)
     {
          string[] addressArray = tempAddress.Split(';');
      string taddr1,taddr2;
      taddr1=addressArray[0];
      Console.Write(taddr1);
      taddr2=addressArray[1];
      Console.Write(taddr2);
     }
     // title
     Console.Write(GetProperty(sResultSet,"title"));
     // company
     Console.Write(GetProperty(sResultSet,"company"));
     //state
     Console.Write(GetProperty(sResultSet,"st"));
     //city
     Console.Write(GetProperty(sResultSet,"l"));
     //country
     Console.Write(GetProperty(sResultSet,"co"));
     //postal code
     Console.Write(GetProperty(sResultSet,"postalCode"));
     // telephonenumber
     Console.Write(GetProperty(sResultSet,"telephoneNumber"));
     //extention
     Console.Write(GetProperty(sResultSet,"otherTelephone"));
    //fax
     Console.Write(GetProperty(sResultSet,"facsimileTelephoneNumber"));
 
    // email address
     Console.Write(GetProperty(sResultSet,"mail"));
     // Challenge Question
     Console.Write(GetProperty(sResultSet,"extensionAttribute1"));
     // Challenge Response
     Console.Write(GetProperty(sResultSet,"extensionAttribute2"));
     //Member Company
     Console.Write(GetProperty(sResultSet,"extensionAttribute3"));
     // Company Relation ship Exits
     Console.Write(GetProperty(sResultSet,"extensionAttribute4"));
     //status
     Console.Write(GetProperty(sResultSet,"extensionAttribute5"));
          // Assigned Sales Person
     Console.Write(GetProperty(sResultSet,"extensionAttribute6"));
     // Accept T and C
     Console.Write(GetProperty(sResultSet,"extensionAttribute7"));
     // jobs
     Console.Write(GetProperty(sResultSet,"extensionAttribute8"));
   String tEamil = GetProperty(sResultSet,"extensionAttribute9");
 
     // email over night
   if(tEamil!=string.Empty)
   {
      string em1,em2,em3;
    string[] emailArray = tEmail.Split(';');
      em1=emailArray[0];
      em2=emailArray[1];
      em3=emailArray[2];
      Console.Write(em1+em2+em3);
      
   }
     // email daily emerging market
     Console.Write(GetProperty(sResultSet,"extensionAttribute10"));
     // email daily corporate market
   Console.Write(GetProperty(sResultSet,"extensionAttribute11"));
     // AssetMgt Range
     Console.Write(GetProperty(sResultSet,"extensionAttribute12"));
     // date of account created
     Console.Write(GetProperty(sResultSet,"whenCreated"));
   // date of account changed
     Console.Write(GetProperty(sResultSet,"whenChanged"));
}

Enjoy.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

rajasekhara sambangi

United States United States
Rajasekhara sambangi has 8 years experience in
software development .
 
Developing .NET,ASP.NET,C#,VB.NET,SQLSERVER AND ORACLE Projects from last 4 years.
 

Comments and Discussions

 
GeneralMy vote of 2 PinmemberMember 17933028-Nov-12 7:19 
SuggestionNice article PinmemberSHAJANCHERIAN7-Aug-12 20:01 
QuestionLogon failure: unknown user name or bad password. Pinmembermurugesan.velusamy14-Jun-12 21:22 
AnswerRe: Logon failure: unknown user name or bad password. PinmemberMember 115155628-Jun-12 22:29 
Questionnice one Pinmemberyasir1152-May-12 19:27 
GeneralMy vote of 2 Pinmembervinakar13-Dec-11 2:06 
GeneralRetrieving the users from Active Directory PinmemberMember 78048561-Apr-11 3:10 
Questionwhere is the all code in zip ?? Pinmemberalhambra-eidos27-Dec-10 23:32 
GeneralMy vote of 1 Pinmembersam_mj8-Jul-10 3:44 
GeneralRe: My vote of 1 PinmemberDjValy19-Oct-10 16:37 
it works...
 
let's say you have a domain account username = DJohn, password = theWorks then the statement you should use is:
 
DirectoryEntry entry = new DirectoryEntry("LDAP://DomainName", "DJohn", "theWorks");
GeneralGetting Active Directory Groups from User Account PinmemberMember 323276622-Apr-09 2:23 
QuestionHi this is phani Pinmembermaganti@phani24-Mar-09 19:58 
Generaleasy application for active directory data retrieval PinmemberMoustafa Deif2-Dec-08 1:00 
GeneralGet currently logged in user list for specific machine using its IP address PinmemberPranjaliBhide3-Jul-08 4:30 
GeneralRe: Get currently logged in user list for specific machine using its IP address Pinmemberaaron vicuna10-Jan-09 17:29 
GeneralRe: Get currently logged in user list for specific machine using its IP address PinmemberPranjaliBhide17-Feb-09 20:23 
GeneralFind 'null' values Pinmemberkeiyia13-Nov-07 10:12 
GeneralStep back PinmemberDan Stoll22-Oct-07 19:02 
AnswerRe: Step back PinmemberSpasticus3-Aug-10 2:58 
GeneralVery Great Article PinmemberIyad Abu Abdu9-Sep-07 6:06 
QuestionQuestion Pinmemberkhan_SharePoint23-Jul-07 5:38 
GeneralGreat example Pinmemberalzikan9-Jul-07 7:00 
GeneralAwesome example Thank you! Pinmemberdberecha2-Apr-07 10:07 
Generalbugs bugs bugs Pinmemberphm3713-Feb-07 5:28 
QuestionActive Directory attributes Pinmemberestevesj26-Sep-06 1:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 21 Apr 2004
Article Copyright 2004 by rajasekhara sambangi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid