How can I get a list of Organizational Units from Active Directory?

delete picture delete · Mar 18, 2011 · Viewed 26.6k times · Source

I've looked into the DirectoryServices class and it seems to be what I need, but I can't seem to find the classes/methods needed to fetch a collection of Organizational Units.

Can you guys give some suggestions?

Answer

marc_s picture marc_s · Mar 18, 2011

You need to use an appropriate DirectorySearcher from System.DirectoryServices, and you need to search for the organizationalUnit AD class (I would recommend searching based on the objectCategory which is single-valued and indexed - much faster than using objectClass) - something like this:

List<string> orgUnits = new List<string>();

DirectoryEntry startingPoint = new DirectoryEntry("LDAP://DC=YourCompany,DC=com");

DirectorySearcher searcher = new DirectorySearcher(startingPoint);
searcher.Filter = "(objectCategory=organizationalUnit)";

foreach (SearchResult res in searcher.FindAll()) 
{
    orgUnits.Add(res.Path);
}