如何获取所有域名列表?

时间:2010-04-07 22:41:27

标签: c# visual-studio-2008 directoryentry

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

2 个答案:

答案 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。您将找到一个简单的代码段来枚举当前林中的域。