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 ...
-
string sRootDomain;
-
System.DirectoryServices.DirectoryEntry deRootDSE;
-
System.DirectoryServices.DirectoryEntry deSearchRoot;
-
System.DirectoryServices.DirectorySearcher dsFindDomains;
-
System.DirectoryServices.SearchResultCollection srcResults;
-
-
sRootDomain = "GC://" + deRootDSE.Properties["rootDomainNamingContext"].Value.ToString();
-
-
dsFindDomains.Filter = "(objectCategory=domainDNS)";
-
dsFindDomains.SearchScope = System.DirectoryServices.SearchScope.Subtree;
-
-
srcResults = dsFindDomains.FindAll();
-
foreach(System.DirectoryServices.SearchResult srDomain in srcResults) {
-
System.Console.WriteLine(srDomain.Properties["name"][0].ToString()
-
+ " - "
-
+ srDomain.Properties["distinguishedName"][0].ToString());
-
}
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.
Hi,
it was a nice one i was looking for the same your effort veru much appreciated.thanks
Thank you very much. I spend much time to look this information. That's great.
Very useful, and quick. Thank you.