Click here to Skip to main content
15,887,434 members
Articles / Programming Languages / C#
Article

How to get User Data from the Active Directory

Rate me:
Please Sign up or sign in to vote.
4.18/5 (43 votes)
20 Apr 20041 min read 668.8K   128   35
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:

C#
String Name="Richmond";

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

C#
// l = city name

Step 6:

C#
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.

C#
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:

C#
// 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


Written By
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
poyesh000@gmail.com11-Nov-21 0:06
poyesh000@gmail.com11-Nov-21 0:06 
GeneralMy vote of 5 Pin
gaurav gujral18-Nov-14 17:28
gaurav gujral18-Nov-14 17:28 
GeneralMy vote of 2 Pin
Sau00228-Nov-12 7:19
Sau00228-Nov-12 7:19 
SuggestionNice article Pin
SHAJANCHERIAN7-Aug-12 20:01
SHAJANCHERIAN7-Aug-12 20:01 
QuestionLogon failure: unknown user name or bad password. Pin
murugesan.velusamy14-Jun-12 21:22
murugesan.velusamy14-Jun-12 21:22 
AnswerRe: Logon failure: unknown user name or bad password. Pin
Member 115155628-Jun-12 22:29
Member 115155628-Jun-12 22:29 
Questionnice one Pin
yasir1152-May-12 19:27
yasir1152-May-12 19:27 
GeneralMy vote of 2 Pin
vinakar13-Dec-11 2:06
vinakar13-Dec-11 2:06 
GeneralRetrieving the users from Active Directory Pin
Member 78048561-Apr-11 3:10
Member 78048561-Apr-11 3:10 
Questionwhere is the all code in zip ?? Pin
kiquenet.com27-Dec-10 23:32
professionalkiquenet.com27-Dec-10 23:32 
GeneralMy vote of 1 Pin
sam_mj8-Jul-10 3:44
sam_mj8-Jul-10 3:44 
GeneralRe: My vote of 1 Pin
DjValy19-Oct-10 16:37
DjValy19-Oct-10 16:37 
GeneralGetting Active Directory Groups from User Account Pin
techbrij22-Apr-09 2:23
techbrij22-Apr-09 2:23 
QuestionHi this is phani Pin
maganti@phani24-Mar-09 19:58
maganti@phani24-Mar-09 19:58 
Generaleasy application for active directory data retrieval Pin
Moustafa Deif2-Dec-08 1:00
Moustafa Deif2-Dec-08 1:00 
GeneralGet currently logged in user list for specific machine using its IP address Pin
PranjaliBhide3-Jul-08 4:30
PranjaliBhide3-Jul-08 4:30 
GeneralRe: Get currently logged in user list for specific machine using its IP address Pin
aaron vicuna10-Jan-09 17:29
aaron vicuna10-Jan-09 17:29 
Hi, it is not possible to retrieve users who are currently logged on in LDAP, Windows server ADSI does not have any field that stores the current activity of each user, but i found a way which will be able to do it, thanks to Jerold Schulman of techarchive.net for the code, here is the url of the code http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.server.scripting/2005-11/msg00417.html[^] the code is a dos shell, but before you can use the code you have to download psLoggedOn on this site http://technet.microsoft.com/en-us/sysinternals/bb897545.aspx[^] it is a collection of useful tools and it includes the said tools.

Here are the steps you can do
1. save this code from Jerold Schulman in your notepad,

@echo off
setlocal
for /f "Skip=1 Tokens=*" %%c in ('dsquery * domainroot -filter "(&(objectCategory=Computer)(objectClass=Computer))" -attr name') do (
for /f "Tokens=*" %%u in ('psLoggedOn -L \\%%c^|find "/"') do (
@echo %%c %%u
)
)
endlocal

2. Save it as userLoggedOn.bat, or anything you like inside system32 folder of your root directory.(I am assuming you are using Windows OS)

3. Download psTools.

4. Extract it in your system32 folder.

5. Run DOS shell and type userLoggedOn.bat or the filename you created with the code above.

If whatsoever you want to integrate it in a program then i developed a code which will be able to list all who logged in per user info here is the code:

'this is the script file

Imports System.Diagnostics
Partial Class Default7
Inherits System.Web.UI.Page

Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
Dim p As New Process
With p.StartInfo
.FileName = "UserOnline.bat"
.RedirectStandardOutput = True
.CreateNoWindow = True
.UseShellExecute = False
End With
p.Start()

Do While Not p.StandardOutput.EndOfStream
MsgBox(p.StandardOutput.ReadLine)
Loop
'end of script

'here is the aspx page

]]>





<title>Untitled Page




<asp:button id="button1" runat="server" text="Process Command" xmlns:asp="#unknown">






' end of aspx page

Hope this will help you. I am not a very good at everything but i have a heart to help thanks.
GeneralRe: Get currently logged in user list for specific machine using its IP address Pin
PranjaliBhide17-Feb-09 20:23
PranjaliBhide17-Feb-09 20:23 
GeneralFind 'null' values Pin
prpleprncs13-Nov-07 10:12
prpleprncs13-Nov-07 10:12 
GeneralStep back Pin
Dan Stoll22-Oct-07 19:02
Dan Stoll22-Oct-07 19:02 
AnswerRe: Step back Pin
Spasticus3-Aug-10 2:58
Spasticus3-Aug-10 2:58 
GeneralVery Great Article Pin
Iyad Abu Abdu9-Sep-07 6:06
Iyad Abu Abdu9-Sep-07 6:06 
QuestionQuestion Pin
khan SharePoint Developer23-Jul-07 5:38
khan SharePoint Developer23-Jul-07 5:38 
GeneralGreat example Pin
alzikan9-Jul-07 7:00
alzikan9-Jul-07 7:00 
GeneralAwesome example Thank you! Pin
dberecha2-Apr-07 10:07
dberecha2-Apr-07 10:07 

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

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