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

发布于 2024-11-06 05:38:06 字数 726 浏览 1 评论 0原文

在 .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 };,但最终根本没有更改设置。

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

I've tried setting both IPs to null, like sIps = { null, null };, but that ends up not changing the settings at all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

[浮城] 2024-11-13 05:38:06

尝试将 DNSServerSearchOrder 设置为 null,而不是使用 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);
     }
  }
}

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);
     }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文