Reputation: 590
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.
How can I do this?
Upvotes: 10
Views: 23322
Reputation: 1947
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.
Forest forest = Forest.GetForest(new DirectoryContext(DirectoryContextType.Forest, "yourForestDomain", "username", "password"));
DomainCollection domains = forest.Domains;
Upvotes: 5
Reputation: 457
You could also use System.DirectoryServices.ActiveDirectory.Forest.GetCurrentForest().Domains
var domains = Forest.GetCurrentForest().Domains.Cast<Domain>();
foreach (var domain in domains)
{
Console.WriteLine(domain.Name);
}
Upvotes: 2
Reputation: 3825
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.
Upvotes: 10
Reputation: 1428
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.
Upvotes: 1