How to get a list of all domains?

I am trying to get all the domains available in the Windows login dialog (in the Domain drop-down list).

I tried the following code, but it only returns the domain that I entered. Did I miss 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; 
+4
source share
2 answers

Add link to System.DirectoryServices.dll

 using (var forest = Forest.GetCurrentForest()) { foreach (Domain domain in forest.Domains) { Debug.WriteLine(domain.Name); domain.Dispose(); } } 
+19
source

Check out this CodeProject article . You will find a simple code snippet for listing domains in the current forest.

+1
source

Source: https://habr.com/ru/post/1306304/


All Articles