如何使用 C# 获取 Active Directory 中所有域的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/323608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get list of all domains in Active Directory using C#
提问by Arun
Can anyone please help me to get all the domains in Active Directory. I have tried many times, but all the programs are listing only the current working domain.
任何人都可以帮助我获取 Active Directory 中的所有域。我试了很多次,但所有的程序都只列出了当前的工作域。
How can I do this?
我怎样才能做到这一点?
回答by Sergiu Damian
Using DirectorySearcher you can connect and read the structure of one Active Directory, including the structure (organization units, groups, users, computers, domain controllers). In order to connect to a different domain, you would need credentials of that other domain. We had problems in connecting to another domain from a machine that belongs to a different domain than the target one. I'm also curious if that's even possible.
使用 DirectorySearcher,您可以连接并读取一个 Active Directory 的结构,包括结构(组织单位、组、用户、计算机、域控制器)。为了连接到不同的域,您需要该其他域的凭据。我们在从属于不同域的机器连接到另一个域时遇到问题,而不是目标机器。我也很好奇这是否可能。
回答by LeeMobile
Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, "yourDomain", "username", "password"));
Forest forest = domain.Forest;
DomainCollection domains = forest.Domains;
The above uses the System.DirectoryServices.ActiveDirectory namespace. It'll give you a domain collection containing all the domains that are in the same forest as your given domain.
以上使用 System.DirectoryServices.ActiveDirectory 命名空间。它将为您提供一个域集合,其中包含与您的给定域位于同一林中的所有域。
回答by Paul
I had some issues getting LeeMobile's code to work in my case bacause it was trying to find my application's current domain context while running forest.Domains. I was able to get around it by doing something like this.
我在让 LeeMobile 的代码在我的案例中工作时遇到了一些问题,因为它在运行 Forest.Domains 时试图找到我的应用程序的当前域上下文。我能够通过做这样的事情来解决它。
Forest forest = Forest.GetForest(new DirectoryContext(DirectoryContextType.Forest, "yourForestDomain", "username", "password"));
DomainCollection domains = forest.Domains;
回答by kotpal
You could also use System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest().Domains
您还可以使用 System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest().Domains
var domains = Forest.GetCurrentForest().Domains.Cast<Domain>();
foreach (var domain in domains)
{
Console.WriteLine(domain.Name);
}