Set DNS to 'Obtain automatically' programmatically
Using C# on .NET, how do I set the DNS servers to 'Obtain automatically'? I can set the IP addresses to desired values like this.
ManagementClass mClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection mObjCol = mClass.GetInstances();
foreach (ManagementObject mObj in mObjCol)
{
if ((bool)mObj["IPEnabled"])
{
ManagementBaseObject mboDNS = mObj.GetMethodParameters("SetDNSServerSearchOrder");
if (mboDNS != null)
{
//Assume X.X.X.X an开发者_如何转开发d X.X.X.X are the IPs.
string[] sIPs = { "X.X.X.X", "X.X.X.X" };
mboDNS["DNSServerSearchOrder"] = sIPs;
mObj.InvokeMethod("SetDNSServerSearchOrder", mboDNS, null);
}
}
}
I've tried setting both IPs to null, like sIps = { null, null };
, but that ends up not changing the settings at all.
Try setting DNSServerSearchOrder to null instead of using an array of null strings.
ManagementClass mClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection mObjCol = mClass.GetInstances();
foreach (ManagementObject mObj in mObjCol)
{
if ((bool)mObj["IPEnabled"])
{
ManagementBaseObject mboDNS = mObj.GetMethodParameters("SetDNSServerSearchOrder");
if (mboDNS != null)
{
mboDNS["DNSServerSearchOrder"] = null;
mObj.InvokeMethod("SetDNSServerSearchOrder", mboDNS, null);
}
}
}
精彩评论