Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine current domain controller programmatically

I need to query current domain controller, probably primary to change user password.

(P)DC name should be fully qualified, i.e. DC=pdc,DC=example,DC=com (how to properly name such notation?)

How can it be done using C#?

like image 227
abatishchev Avatar asked Oct 25 '10 14:10

abatishchev


People also ask

How do I identify my domain controller?

If you just desire to identify which domain controller the user retrieved group policies from you can type gpresult /r. The returned results will provide you the name of the domain controller that provided the logged on user with GPOs.

How do you check if a machine is a domain controller?

Concluding. Using the DomainRole property of the ComputerSystem class is a useful and fast way to check whether a Server Core installation of Windows Server is a Domain Controller, whether it's domain-joined and whether it holds the PDCe FSMO role.


2 Answers

To retrieve the information when the DomainController exists in a Domain in which your machine doesn't belong, you need something more.

  DirectoryContext domainContext =  new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");

  var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
  var controller = domain.FindDomainController();
like image 75
Brett Veenstra Avatar answered Oct 30 '22 23:10

Brett Veenstra


We are using something like this for our internal applications.

Should return something like DC=d,DC=r,DC=ABC,DC=com

public static string RetrieveRootDseDefaultNamingContext()
{
    String RootDsePath = "LDAP://RootDSE";
    const string DefaultNamingContextPropertyName = "defaultNamingContext";

    DirectoryEntry rootDse = new DirectoryEntry(RootDsePath)
    {
        AuthenticationType = AuthenticationTypes.Secure;
    };
    object propertyValue = rootDse.Properties[DefaultNamingContextPropertyName].Value;

    return propertyValue != null ? propertyValue.ToString() : null;
}
like image 43
Lareau Avatar answered Oct 30 '22 21:10

Lareau