Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Yesterday, I was with a colleague and we were discussing how to set an IP address to be static for a particular use case and then go back to being dynamic. We discussed netsh and PowerShell, but I just wanted to see if we could achieve it in C# code. So, just in case anybody else requires it, here it is.
I have made this code only change the settings for the adapter based on it’s description as obviously you wouldn’t want to change all of your adapters and will allow you to test the code.
string myDesc = "Intel(R) Centrino(R) Advanced-N 6205";
string gateway = "192.168.0.1";
string subnetMask = "255.255.255.0";
string address = "192.168.0.10";
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) == 0)
{
try
{
// Set DefaultGateway
var newGateway = adapter.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
// Set IPAddress and Subnet Mask
var newAddress = adapter.GetMethodParameters("EnableStatic");
newAddress["IPAddress"] = new string[] { address };
newAddress["SubnetMask"] = new string[] { subnetMask };
adapter.InvokeMethod("EnableStatic", newAddress, null);
adapter.InvokeMethod("SetGateways", newGateway, null);
Console.WriteLine("Updated to static IP address!");
}
catch (Exception ex)
{
Console.WriteLine("Unable to Set IP : " + ex.Message);
}
}
}
string myDesc = "Intel(R) Centrino(R) Advanced-N 6205";
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) == 0)
{
try
{
adapter.InvokeMethod("EnableDHCP", null);
Console.WriteLine("Updated Dynamic address!");
}
catch (Exception ex)
{
Console.WriteLine("Unable to Set IP : " + ex.Message);
}
}
}
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in