将DNS设置为以编程方式“自动获取”

时间:2011-05-11 08:24:43

标签: c# .net winforms networking dns

在.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 };,但最终不会更改设置。

1 个答案:

答案 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);
     }
  }
}