5

我正在尝试获取 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;
4

2 回答 2

22

添加对 System.DirectoryServices.dll 的引用

using (var forest = Forest.GetCurrentForest())
{
    foreach (Domain domain in forest.Domains)
    {
        Debug.WriteLine(domain.Name);
        domain.Dispose();
    }
}
于 2010-04-08T03:09:17.360 回答
2

看看这篇 CodeProject 文章。您将找到一个简单的代码片段来枚举当前林中的域。

于 2010-04-07T23:50:13.377 回答