Arun
Arun

Reputation: 590

How to get list of all domains in Active Directory using C#

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

Answers (4)

Paul
Paul

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

kotpal
kotpal

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

LeeMobile
LeeMobile

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

Sergiu Damian
Sergiu Damian

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

Related Questions