dimanche 10 mai 2015

Changing DNS (C#, WPF) is not working

I want to change NETWORK CONFIGURATION programmatically. Everything is working fine, only IP of DNS doesn't want to change, it stays empty.

I use next code to change configuration:

        public void setDNS(string NIC, string DNS)
        {
            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();

            foreach (ManagementObject objMO in objMOC)
            {
                if ((bool)objMO["IPEnabled"])
                {
                    // if you are using the System.Net.NetworkInformation.NetworkInterface you'll need to change this line to if (objMO["Caption"].ToString().Contains(NIC)) and pass in the Description property instead of the name 
                    //if (objMO["Caption"].Equals(NIC))
                    if (objMO["Caption"].ToString().Contains(NIC))
                    {
                        try
                        {
                            ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                            newDNS["DNSServerSearchOrder"] = DNS.Split('.');
                            ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                }
            }
        }        
    }
}

Aucun commentaire:

Enregistrer un commentaire