65.9K
CodeProject is changing. Read more.
Home

Accessing Active Directory Objects via C# (Visual Studio)

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Jan 27, 2011

CPOL
viewsIcon

63773

Accessing Active Directory Objects via C# (Visual Studio)

Background This is an article for a beginner to learn how to access Active directory objects via C# code. Using the Code To use the code, you would need a Windows server with Active Directory installed and Visual Studio on your machine. System References Make sure you have included the following namespaces in your code:
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
Directory Entry Object Now we create a directory entry object for our Active directory.
DirectoryEntry dir = new DirectoryEntry("LDAP://your_domain_name");
Creating a Search Object and Executing the Search The DirectorySearcher object searches the Active directory. You can set the filter property to retrieve specific records. I am also using the AND "&" property to combine two conditions.
DirectorySearcher search = new DirectorySearcher(dir);

search.Filter = "(&(objectClass=user)(givenname=First_Name))";
Handling Search Results Firstly, we create a SearchResult object to get the data from the search. Next, I have shown how to get all the property names for that object, which can be later used to get any particular property value. Finally, we get the directory entry from the Search Result and then specify a particular property name to get its value.
SearchResult searchresult = search.FindOne(); // You can also use the FindAll() method for multiple objects.

   if (searchresult != null)
   {
	foreach(System.Collections.DictionaryEntry direntry in searchresult.Properties) 
                    TextBox1.Text += direntry.Key.ToString() +"\n"; // This will give you all the property names that are set for that particular object,which you can use to get a specific value.I have used a Multiline textbox here.			      

        TextBox1.Text += searchresult.GetDirectoryEntry().Properties["sn"].Value.ToString(); // I am displaying the lastname/surname in simple textbox.
   }
Points of Interest I hope this article will help beginners to get to know how to access Active Directory objects through C# code.