以编程方式将 DNS 设置为“自动获取”
本文关键字:获取 自动获取 方式 编程 DNS 设置 | 更新日期: 2023-09-27 17:56:19
在.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 都设置为 null,例如 sIps = { null, null };
,但这最终根本没有更改设置。
尝试将 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);
}
}
}