C# Remove Preffered DNS server address?

September 21, 2011 at 07:08:19
Specs: Windows 7, 4GB
Im currently setting Preferred DNS server by this code:
        public bool setDNS(string dns)
        {
            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();

            foreach (ManagementObject objMO in objMOC)
            {
                if ((bool)objMO["IPEnabled"])
                {

                    string Description = objMO["Description"].ToString();

                    if (Description.Contains("Wireless"))
                        continue;

                    // Set Preferred DNS
                    try
                    {
                        ManagementBaseObject newDNS =
                                             objMO.GetMethodParameters("SetDNSServerSearchOrder");
                        newDNS["DNSServerSearchOrder"] = dns.Split(',');
                        ManagementBaseObject setDNS =
                            objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);

                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Preferred DNS set failed");
                        return false;
                    }
                }
            }

            return true;
        }

It is called by:
            string dns = "207.13.251.4";
            bool test = setDNS(dns);
            Console.WriteLine("Test {0}", test);
            Application.Exit();
This works fine setting to IP address above. However if I do this, it does not blank the address in error:
            string dns = ",";
            bool test = setDNS(dns);
            Console.WriteLine("Test {0}",test);
            Application.Exit();
I have a method above which sets the Preferred DNS server correctly, but I need a method to remove it?

Thanks,

Andrew

edited by moderator: Formatting -Razor2.3


See More: C# Remove Preffered DNS server address?

Report •


#1
September 21, 2011 at 07:25:27
I have also tried this but it does not work either:
code:

string dns = "0.0.0.0,0.0.0.0";
bool test = setDNS(dns);


Report •

#2
September 26, 2011 at 02:34:44
Solved with this code:

if (dns == "," || dns == "") // Empty DNS server

newDNS["DNSServerSearchOrder"] = new string[0];


else


newDNS["DNSServerSearchOrder"] = dns.Split(',');


ManagementBaseObject setDNS =

objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);


Report •
Related Solutions


Ask Question