Why does applying a static IP address via WMI work just once?

青春壹個敷衍的年華 提交于 2020-01-03 00:54:30

问题


I'm about to write a simple network configuration tool which can either set IP address and so on statically or let it be set automatically (DHCP), all by means of WMI.

Unfortunately, setting the address statically works just once! So when you run the test function below once, everything works perfect (don't forget a breakpoint at // DYNAMIC!). But at the second time and when you check the results in the control panel's properties page of the network adapter IP address and subnet mask remain empty! Of course there are no exceptions thrown and the result of the method invocation is always zero (0). The code was tested on two different Windows 7 machines and of course as administrator.

void Test()
{

    // find management object
    ManagementClass networkManagementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection networkManagement = networkManagementClass.GetInstances();
    ManagementObject adapter = null;
    foreach (ManagementObject mo in networkManagement)
    {
        if ((bool)mo["IPEnabled"] && (string)mo["Caption"] == "[00000012] Intel(R) 82577LM Gigabit Network Connection")
        {
            adapter = mo;
            break;
        }
    }

    // STATIC

    var val = adapter.InvokeMethod("EnableStatic", new object[] {
        new string[] { "192.168.1.99" },
        new string[] { "255.255.255.0" }
    });

    val = adapter.InvokeMethod("SetGateways", new object[] {
        new string[] { "192.168.1.254" },
        new UInt16[] { 1 }
    });

    val = adapter.InvokeMethod("SetDNSServerSearchOrder", new object[] {
        new string[] { "192.168.1.254" }
    });

    // DYNAMIC

    adapter.InvokeMethod("SetDNSServerSearchOrder", new object[] { new string[0] });

    adapter.InvokeMethod("EnableDHCP", new object[] { });

}

回答1:


Finally I figured out a workaround for this (i guess) Windows bug: Fill the right values into the registry DIRECTLY and BEFORE the WMI calls:

// workaround of windows bug (windows refused to apply static ip in network properties dialog)
var settingID = adapter.GetPropertyValue("SettingID"); // adapter = the management object
using (var regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\" + settingID, true))
{
    regKey.SetValue("EnableDHCP", 0);
    regKey.SetValue("IPAddress", networkState.IPAddress, RegistryValueKind.MultiString);
    regKey.SetValue("SubnetMask", networkState.SubnetMask, RegistryValueKind.MultiString);
}

Works like a charm for me. Have fun :)



来源:https://stackoverflow.com/questions/11613196/why-does-applying-a-static-ip-address-via-wmi-work-just-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!