How Can I Get a List of All the Domains in a Forest

Here’s a sample C# code that searches for all the domain objects.
Because we want to search the global catalog we need to use the global catalog provider. Thus instead of specifying LDAP: in our binding string we specify GC.

static void Main(string[] args)
{
	DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
	String gcPath = rootDSE.Properties["rootDomainNamingContext"].Value.ToString();
	DirectoryEntry gcRoot = new DirectoryEntry("GC://" + gcPath);

	DirectorySearcher ds = new DirectorySearcher();
	ds.SearchRoot = gcRoot;
	ds.SearchScope = SearchScope.OneLevel;
	ds.PageSize = 200;
	ds.CacheResults = false;
	ds.ClientTimeout = TimeSpan.FromSeconds(60);
	ds.Filter = "(&(objectClass=domain))";
	ds.PropertiesToLoad.Add("DC");
	ds.PropertiesToLoad.Add("distinguishedName");

	SearchResultCollection src = ds.FindAll();
	foreach (SearchResult result in src)
	{
		if (result.Properties.Contains("DC"))
		{
			Console.WriteLine((string)result.Properties["distinguishedName"][0]);
		}
	}
}

With .NET Framework 4.5 there is a very simple way to get all domains in the forest by using the class System.DirectoryServices.ActiveDirectory.Forest

static void Main(string[] args)
{
	using (Forest forest = Forest.GetCurrentForest())
	{
		Console.WriteLine("Forest:  {0}", forest.Name);
		foreach (Domain domain in forest.Domains)
		{
			Console.WriteLine(String.Format("Domain:  {0}", domain.Name));
			domain.Dispose();
		}
	}
}

Speak Your Mind

*