5

I'm trying to get all domains that are available in the Windows Login dialog (in the Domain dropdown).

I've tried the following code but it only returns the domain I am logged into. Am I missing something?

StringCollection domainList = new StringCollection();
try
{
    DirectoryEntry en = new DirectoryEntry();
    // Search for objectCategory type "Domain"
    DirectorySearcher srch = new DirectorySearcher(en, "objectCategory=Domain");
    SearchResultCollection coll = srch.FindAll();
    // Enumerate over each returned domain.
    foreach (SearchResult rs in coll)
    {
        ResultPropertyCollection resultPropColl = rs.Properties;
        foreach( object domainName in resultPropColl["name"])
        {
            domainList.Add(domainName.ToString());
        }
    }
}
catch (Exception ex)
{
    Trace.Write(ex.Message);
}
return domainList;
AngryHacker
  • 59,598
  • 102
  • 325
  • 594

2 Answers2

22

Add a reference to System.DirectoryServices.dll

using (var forest = Forest.GetCurrentForest())
{
    foreach (Domain domain in forest.Domains)
    {
        Debug.WriteLine(domain.Name);
        domain.Dispose();
    }
}
Simon
  • 33,714
  • 21
  • 133
  • 202
  • I had to add "using System.DirectoryServices.ActiveDirectory;" to pickup the Forest objects. – shawad Aug 02 '18 at 09:59
2

Take a look at this CodeProject article. You'll find a simple code snippet to enumerate domains in the current forest.

Phileosophos
  • 304
  • 1
  • 6