在.NET上使用C#,如何将DNS服务器设置为“自动获取”?我可以将IP地址设置为所需的值。
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 and 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);
}
}
}
我已尝试将两个IP设置为空,例如sIps = { null, null };
,但最终不会更改设置。
答案 0 :(得分:7)
尝试将DNSServerSearchOrder设置为null,而不是使用空字符串数组。
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);
}
}
}