How to list all available Active Directory domains using .NET

Here is an example of .NET code that uses the System.DirectoryServices.ActiveDirectory namespace to list all available Active Directory domains:

using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;

namespace ActiveDirectoryDomains
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the current forest
            Forest currentForest = Forest.GetCurrentForest();

            // Get a collection of all the domains in the forest
            DomainCollection domains = currentForest.Domains;

            // Print the name of each domain
            Console.WriteLine("Available Active Directory domains:");
            foreach (Domain domain in domains)
            {
                Console.WriteLine("- " + domain.Name);
            }
        }
    }
}

This code uses the GetCurrentForest method to get the current forest and the Domains property to get a collection of all the domains in the forest. It then iterates through the collection and prints the name of each domain to the console. Note that you will need to have appropriate permissions to query Active Directory domains.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2025 Pamai Tech