Setting an IP to address to be static and then dynamic in C#

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.

Setting a static IP address

 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);
        }
    }
}

Setting a dynamic IP address

 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);
        }
    }
}