Skip to content

Getting list of (sub-)domains from Active Directory with C#

Some days ago I needed some piece of c# code to list all domains with subdomains from Active Directory.
My first idea was to bind to the LDAP port. After some tests I was confused because I always got only one search result. The LDAP port did not give out info for other domains, just the domain i bound to. After some time I figured out that I need to bind to the GC port.

So here's some code snippet to list all domains (with subdomains) from Active Directory. Maybe someone finds this useful ...

C#:
  1. string sRootDomain;
  2. System.DirectoryServices.DirectoryEntry deRootDSE;
  3. System.DirectoryServices.DirectoryEntry deSearchRoot;
  4. System.DirectoryServices.DirectorySearcher dsFindDomains;
  5. System.DirectoryServices.SearchResultCollection srcResults;
  6.  
  7. deRootDSE = new System.DirectoryServices.DirectoryEntry("GC://RootDSE");
  8. sRootDomain = "GC://" + deRootDSE.Properties["rootDomainNamingContext"].Value.ToString();
  9.  
  10. deSearchRoot = new System.DirectoryServices.DirectoryEntry(sRootDomain);
  11. dsFindDomains = new System.DirectoryServices.DirectorySearcher(deSearchRoot);
  12. dsFindDomains.Filter = "(objectCategory=domainDNS)";
  13. dsFindDomains.SearchScope = System.DirectoryServices.SearchScope.Subtree;
  14.  
  15. srcResults = dsFindDomains.FindAll();
  16. foreach(System.DirectoryServices.SearchResult srDomain in srcResults) {
  17.     System.Console.WriteLine(srDomain.Properties["name"][0].ToString()
  18.         + " - "
  19.         + srDomain.Properties["distinguishedName"][0].ToString());
  20. }

At last one word about the filter (objectCategory=domainDNS):
First I used a filter like (objectClass=domainDNS). I decided to change this for the following reason:
I wanted to use an indexed criteria for the search. A filter of objectClass=domainDNS would involve looking at every single object in the tree and checking objectClass which could take a long time (of course, this depends on the forest and the DC performance). Using objectCategory=domainDNS should return within a few seconds on any hardware/forest.

Categories: Programming.

Tags: , ,

Comment Feed

3 Responses

  1. Hi,
    it was a nice one i was looking for the same your effort veru much appreciated.thanks

    RajeevJune 12, 2008 @ 8:44 am
  2. Thank you very much. I spend much time to look this information. That's great.

    Quoc DungSeptember 25, 2008 @ 3:41 pm
  3. Very useful, and quick. Thank you.

    SleepwalkerOctober 20, 2008 @ 4:13 pm



Some HTML is OK

or, reply to this post via trackback.