Reading list of users from an Active Directory domain with C#
Posted: (EET/GMT+2)
I needed to write a simple C# application that reads me the names of user accounts in an Active Directory domain (Windows Server 2003 based domain). The .NET class library contains a whole namespace dedicated to directories: System.DirectoryServices. This namespace contains a class called DirectoryEntry that you can use to read the user accounts in a given organizational unit (OU). Here's the example code:
using System.DirectoryServices;
private void ReadActiveDirectory()
{
string path = "LDAP://OU=ChildOU,OU=TopLevelOU,DC=mycompany,DC=local";
DirectoryEntry entry = new DirectoryEntry(path);
foreach (DirectoryEntry child in entry.Children)
{
textBox1.Text += child.Name+"\r\n";
}
}
Here, the most important thing is of course the LDAP "URL", which starts with the string "LDAP://". Note: it is very important that you write the word "LDAP://" with upper-case (capital) letters. If you don't, you will get a binding error at runtime.
To help you solve this problem, here are the details what happens if you type in for example "ldap://" by accident. The error is:
{"Unknown error (0x80005000)"}
{System.Collections.ListDictionaryInternal}
ErrorCode -2147463168
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
In short: don't do it! Other than that, using the Active Directory from .NET is quite simple. And if you are using .NET 2.0 (you should), then you can also utilize the new namespace System.DirectoryServices.ActiveDirectory. Happy ADSI (Active Directory Service Interfaces) programming!