Click here to Skip to main content
11,434,743 members (42,918 online)
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

Share

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 5 Pin
gaurav gujral18-Nov-14 18:28
membergaurav gujral18-Nov-14 18:28 
GeneralMy vote of 2 Pin
Member 17933028-Nov-12 8:19
memberMember 17933028-Nov-12 8:19 
SuggestionNice article Pin
SHAJANCHERIAN7-Aug-12 21:01
memberSHAJANCHERIAN7-Aug-12 21:01 
QuestionLogon failure: unknown user name or bad password. Pin
murugesan.velusamy14-Jun-12 22:22
membermurugesan.velusamy14-Jun-12 22:22 
AnswerRe: Logon failure: unknown user name or bad password. Pin
Member 115155628-Jun-12 23:29
memberMember 115155628-Jun-12 23:29 
Questionnice one Pin
yasir1152-May-12 20:27
memberyasir1152-May-12 20:27 
GeneralMy vote of 2 Pin
vinakar13-Dec-11 3:06
membervinakar13-Dec-11 3:06 
GeneralRetrieving the users from Active Directory Pin
Member 78048561-Apr-11 4:10
memberMember 78048561-Apr-11 4:10 
Questionwhere is the all code in zip ?? Pin
alhambra-eidos28-Dec-10 0:32
memberalhambra-eidos28-Dec-10 0:32 
GeneralMy vote of 1 Pin
sam_mj8-Jul-10 4:44
membersam_mj8-Jul-10 4:44 
GeneralRe: My vote of 1 Pin
DjValy19-Oct-10 17:37
memberDjValy19-Oct-10 17:37 
GeneralGetting Active Directory Groups from User Account Pin
Member 323276622-Apr-09 3:23
memberMember 323276622-Apr-09 3:23 
QuestionHi this is phani Pin
maganti@phani24-Mar-09 20:58
membermaganti@phani24-Mar-09 20:58 
Generaleasy application for active directory data retrieval Pin
Moustafa Deif2-Dec-08 2:00
memberMoustafa Deif2-Dec-08 2:00 
GeneralGet currently logged in user list for specific machine using its IP address Pin
PranjaliBhide3-Jul-08 5:30
memberPranjaliBhide3-Jul-08 5:30 
GeneralRe: Get currently logged in user list for specific machine using its IP address Pin
aaron vicuna10-Jan-09 18:29
memberaaron vicuna10-Jan-09 18:29 
GeneralRe: Get currently logged in user list for specific machine using its IP address Pin
PranjaliBhide17-Feb-09 21:23
memberPranjaliBhide17-Feb-09 21:23 
GeneralFind 'null' values Pin
keiyia13-Nov-07 11:12
memberkeiyia13-Nov-07 11:12 
GeneralStep back Pin
Dan Stoll22-Oct-07 20:02
memberDan Stoll22-Oct-07 20:02 
AnswerRe: Step back Pin
Spasticus3-Aug-10 3:58
memberSpasticus3-Aug-10 3:58 
GeneralVery Great Article Pin
Iyad Abu Abdu9-Sep-07 7:06
memberIyad Abu Abdu9-Sep-07 7:06 
QuestionQuestion Pin
khan_SharePoint23-Jul-07 6:38
memberkhan_SharePoint23-Jul-07 6:38 
GeneralGreat example Pin
alzikan9-Jul-07 8:00
memberalzikan9-Jul-07 8:00 
GeneralAwesome example Thank you! Pin
dberecha2-Apr-07 11:07
memberdberecha2-Apr-07 11:07 
Generalbugs bugs bugs Pin
phm3713-Feb-07 6:28
memberphm3713-Feb-07 6:28 
QuestionActive Directory attributes Pin
estevesj26-Sep-06 2:37
memberestevesj26-Sep-06 2:37 
Question??? Pin
Michael Sync14-Sep-06 0:54
memberMichael Sync14-Sep-06 0:54 
Questionrecieving err:System.Runtime.InteropServices.COMException: The server is not operational [modified] Pin
kpsetty26-May-06 3:30
memberkpsetty26-May-06 3:30 
AnswerRe: recieving err:System.Runtime.InteropServices.COMException: The server is not operational Pin
cksat122-Jun-07 0:58
membercksat122-Jun-07 0:58 
GeneralRe: recieving err:System.Runtime.InteropServices.COMException: The server is not operational Pin
Kombu12-Mar-08 8:44
memberKombu12-Mar-08 8:44 
GeneralRe: recieving err:System.Runtime.InteropServices.COMException: The server is not operational Pin
vasillis_zayetsav15-Apr-09 7:16
membervasillis_zayetsav15-Apr-09 7:16 
GeneralRe: recieving err:System.Runtime.InteropServices.COMException: The server is not operational Pin
DjValy7-Jan-10 18:59
memberDjValy7-Jan-10 18:59 
Generalnice but shame about the typos Pin
Simon Steed (MadSi)6-Jun-05 23:57
memberSimon Steed (MadSi)6-Jun-05 23:57 
GeneralExcellent article Pin
kinsgley1-Jun-05 5:52
susskinsgley1-Jun-05 5:52 

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 | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 21 Apr 2004
Article Copyright 2004 by rajasekhara sambangi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid