We can determine whether the current machine is domain controller or not by checking Domain Role of the computer in Active Directory environment. We can also ensure if the machine DC or not by checking the Active Directory Domain Services is installed or not in current system.
Check if current machine is DC or not by Domain Role in C#
The below C# code retrieve the Domain Role information of current machine using the WMI class Win32_ComputerSystem. If the value of Domain Role is greater than 3 then the machine is domain controller or else, it is just a computer or member server.
using System.Management; //---------------- public static bool IsThisMachineIsDC() { bool is_this_DC = false; try { ManagementScope wmiScope = new ManagementScope(@".rootcimv2"); wmiScope.Connect(); ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(wmiScope, new ObjectQuery("SELECT DomainRole FROM Win32_ComputerSystem")); foreach (ManagementObject shareData in moSearcher.Get()) { int domainRole = int.Parse(shareData["DomainRole"].ToString()); if (domainRole >= 4) { is_this_DC = true; } break; } } catch (Exception ex) { } return is_this_DC; }
Check if current computer is DC or not by Active Directory Domain Services
The below C# code checks if the Active Directory Domain Services is installed or not by using the WMI class Win32_ServerFeature.
using System.Management; //---------------- public static bool IsThisMachineIsDC() { bool is_this_DC = false; try { uint uID = 110; string search = string.Format("SELECT * FROM Win32_ServerFeature WHERE ID = 110", uID); ManagementObjectSearcher moSearcher = new ManagementObjectSearcher("rootCIMV2", search); foreach (var output in moSearcher.Get()) { if ((uint)(output["ID"]) == uID) { is_this_DC = true; break; } } } catch (Exception) { } return is_this_DC; }
Advertisement