2010-04-07 19 views
4

我正在嘗試獲取Windows登錄對話框中可用的所有域(在域下拉列表中)。如何獲取所有域名的列表?

我試過下面的代碼,但它只返回我登錄到的域。我錯過了什麼嗎?

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; 
+0

我可能失去了一些東西,但你似乎沒有用不完的DirectoryEntry恩。 – JYelton 2010-04-07 22:42:50

+0

對不起,代碼修正了。仍然是同樣的結果。 – AngryHacker 2010-04-07 23:49:43

回答

19

添加引用System.DirectoryServices.dll程序

using (var forest = Forest.GetCurrentForest()) 
{ 
    foreach (Domain domain in forest.Domains) 
    { 
     Debug.WriteLine(domain.Name); 
     domain.Dispose(); 
    } 
} 
相關問題