I've seen a lot of code that allows me to set the IP address of a local workstation, but it only works if the workstation already has a static IP address. I need to change the adapter settings from obtaining an IP address automatically to using a static IP I give it.
The code I'm using now is below. It fails on the first if statement for every objMO. I know at least one adapter has IPv4 enbled (I can see it in the Network and Sharing Center), but, like I said, it is set to obtain the IP address automatically:
protected static void ChangeIPAndSubnet( IPAddress ipToSet, IPAddress subnetToSet )
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
// change the IP for all active ManagementObjects
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
try
{
ManagementBaseObject setIP;
ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");
// it's too bad that we have nice, neat ip addresses to use, only to change them
// back to strings, but that's how this code works
string ip_address = ipToSet.ToString();
string subnet_mask = subnetToSet.ToString();
newIP["IPAddress"] = new string[] { ip_address };
newIP["SubnetMask"] = new string[] { subnet_mask };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
}
catch (Exception)
{
// report error
string strError = "The IP Address and/or Subnet mask could not be changed.\n";
strError += "Please check the values and try again";
MessageBox.Show(strError, "Settings Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
How do I change the adapter settings to use an IP address (and subnet mask) I give it?