【问题标题】:Changing DNS (C#, .NET) is not working更改 DNS(C#、.NET)不起作用
【发布时间】:2015-05-10 09:40:36
【问题描述】:

我想以编程方式更改网络配置。一切正常,只有 DNS 的 IP 不想更改,它保持为空。

我使用下一个代码来更改配置:

public void setDNS(string NIC, string DNS)
{
    ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMC.GetInstances();

    foreach (ManagementObject objMO in objMOC)
    {
    if ((bool)objMO["IPEnabled"])
    {
        // if you are using the System.Net.NetworkInformation.NetworkInterface you'll need to change this line to if (objMO["Caption"].ToString().Contains(NIC)) and pass in the Description property instead of the name 
        //if (objMO["Caption"].Equals(NIC))
        if (objMO["Caption"].ToString().Contains(NIC))
        {
            try
            {
                ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder");
                newDNS["DNSServerSearchOrder"] = DNS.Split('.');
                ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
    }
}

【问题讨论】:

  • IP 地址用'.' 分隔,所以用'.' (DNS.Split('.');) 分隔在我看来很可疑。
  • 但我在 DNS 中有带“点”的数字拆分。我也尝试用逗号,但也没有成功。

标签: c# .net dns network-programming


【解决方案1】:

如果您只有一个 DNS IP 地址,则需要将值分配为

newDNS["DNSServerSearchOrder"] = 新字符串[]{DNS};

如果您有两个 DNS IP 地址并且它们之间用 ';' 分隔,则需要将值分配为

newDNS["DNSServerSearchOrder"] = DNS.Split(';');

输入值必须是字符串数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    相关资源
    最近更新 更多