我正在尝试获取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 :(得分:22)
添加对System.DirectoryServices.dll的引用
using (var forest = Forest.GetCurrentForest())
{
foreach (Domain domain in forest.Domains)
{
Debug.WriteLine(domain.Name);
domain.Dispose();
}
}
答案 1 :(得分:1)
看看this CodeProject article。您将找到一个简单的代码段来枚举当前林中的域。