C# – Identify Current Domain Controller Name

c

I'm attempting to get the current domain controller name via c#. This code will NOT be running during a logon session. It runs during machine startup so, I can't use the %logonserver% variable because there is no such thing at machine startup. Searching here I thought the following code would work but it returns the primary domain controller, not the current logon server. (at startup the 'logon server' might be best referred to as the 'authentication server')

this doesn't work for me (doesn't return machines' current DC, returns Domain's PDC)

    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
        {
            string controller = context.ConnectedServer;
            Console.WriteLine("Domain Controller: " + controller);
        }

I have found that the following WMI query gets positive results but, it's slow:

ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\CIMV2",
"SELECT * FROM Win32_NTDomain");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                if (queryObj["DomainControllerName"] != "")
                  Console.WriteLine("DomainControllerName: {0}", queryObj["DomainControllerName"]);
            }

Anyone know a better way?

Best Answer

Granted you'll need to include a user and password, but this should do the trick:

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

  var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
  var controller = domain.FindDomainController();