1

我即将写一个简单的网络配置工具,它可以静态设置IP地址等,也可以让它自动设置(DHCP),全部通过WMI。

不幸的是,静态设置地址只工作一次!因此,当您运行下面的测试函数一次时,一切正常(不要忘记 // DYNAMIC 处的断点!)。但是第二次查看控制面板属性页中的网络适配器IP地址和子网掩码的结果仍然是空的!当然不会抛出异常,并且方法调用的结果始终为零 (0)。该代码在两台不同的 Windows 7 机器上进行了测试,当然也以管理员身份进行了测试。

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[] { });

}
4

1 回答 1

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 :)

于 2012-08-10T17:08:28.187 回答