Reputation: 1462
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[] { });
}
Upvotes: 1
Views: 3481
Reputation: 1462
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 :)
Upvotes: 1