Udostępnij za pośrednictwem


Set DNS server Addresses Progamatically

To just read quickly individual DNS and Network configuration properties you can use the System.Net.NetworkInformation to help.

Create your NW information class. 

NetworkInterface[] nw = NetworkInterface.GetAllNetworkInterfaces();

This returns the first DNS entry as a string.->     nw[0].GetIPProperties().DnsAddresses[0].ToString().

You can obviously expand massively on this, just refer to MSDN.

If you need to set The DNS entries programtically you should use WMI(You have loads of functionality for reading and setting Im just showing the DNS piece here). An example below should help you do this. This method makes sure the device it finds is an IP enabled device and matches the NIC. Apologies for the formatting i cant get it right but you get the idea! it sets both DNS  IP addresses's to the fictitious(111.11.11.12 & 111.11.11.11)

        public void SetDnsConfig()

        {

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

            ManagementObjectCollection moc = mc.GetInstances();

            string nic = string.Empty;

            foreach (ManagementObject mo in moc)

            {

                if ((bool)mo["ipEnabled"])

                {

                    nic = mo["Caption"].ToString();

                    if ((bool)mo["IPEnabled"])

                    {

                        if (mo["Caption"].Equals(nic))

                        {

                            ManagementBaseObject DnsEntry = mo.GetMethodParameters("SetDNSServerSearchOrder");

                  

DnsEntry["DNSServerSearchOrder"] = "111.11.11.11,111.11.11.11".Split(',');//Two ip addresses you want to set         

ManagementBaseObject DnsMbo = mo.InvokeMethod("SetDNSServerSearchOrder", DnsEntry, null);

int returnCode = int.Parse(DnsMbo ["returnvalue"].ToString));//This will give you the return code you can use to evaluate if its not working

break;

                        }

                    }

                }

            }

 

Hope this helps:-)