设置网关使用c#在我的适配器中不起作用

时间:2017-06-30 18:53:29

标签: c#

我的代码旨在更改/设置我的网关值。该程序运行顺畅,但是当我查看我的IPV4设置时,它似乎没有任何改变。我错过了什么?

    public void setGateway(string gateway = "192.168.1.254", string myDesc = "Intel(R) Ethernet Connection (2) I219-V")
    {
        var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
        var networkCollection = adapterConfig.GetInstances();

        foreach(ManagementObject adapter in networkCollection)
        {
            string description = adapter["Description"] as string;
            if(string.Compare(description, myDesc, StringComparison.InvariantCultureIgnoreCase) >= 1)
            {
                try
                {
                    var newGateway = adapter.GetMethodParameters("SetGateways");
                    newGateway["DefaultIPGateway"] = new string[] { gateway };
                    newGateway["GatewayCostMetric"] = new int[] { 1 };

                    adapter.InvokeMethod("SetGateways", newGateway, null);                 
                }
                catch
                {
                    throw;                      
                }
            }
        }
    }

我也在这个链接How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#中提到过,我现在有点困惑,我已经设置了静态IP地址和网络掩码。

0 个答案:

没有答案