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();
if (searchresult != null)
{
foreach(System.Collections.DictionaryEntry direntry in searchresult.Properties)
TextBox1.Text += direntry.Key.ToString() +"\n";
TextBox1.Text += searchresult.GetDirectoryEntry().Properties["sn"].Value.ToString();
}
Points of Interest
I hope this article will help beginners to get to know how to access Active Directory objects through C# code.