1

I have code that is meant to change/set my gateway values. The program runs smoothly, but it doesn't appear to have changed anything when I look at my IPV4 settings. What am I missing?

    public void setGateway(string gateway = "192.168.1.254", string myDesc = "Intel(R) Ethernet Connection (2) I219-V")
    {
        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) >= 1)
            {
                try
                {
                    var newGateway = adapter.GetMethodParameters("SetGateways");
                    newGateway["DefaultIPGateway"] = new string[] { gateway };
                    newGateway["GatewayCostMetric"] = new int[] { 1 };

                    adapter.InvokeMethod("SetGateways", newGateway, null);                 
                }
                catch
                {
                    throw;                      
                }
            }
        }
    }

Also I referred in this link How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#, I'm a bit confused right now, I have a static ip address and netmask already set.

David
  • 4,665
  • 4
  • 34
  • 60
EnnT
  • 35
  • 1
  • 9
  • You probably want to check the return value of the method - _"Returns a value of 0 (zero) for a successful completion when a reboot is not required, 1 (one) for a successful completion when a reboot is required, and any other value if there is an error."_ – stuartd Jun 30 '17 at 18:57
  • I tried `==0` instead of `>=1` but nothing happened again. – EnnT Jun 30 '17 at 19:02
  • Sorry, commenting on my phone - I meant the return value of `SetGateways` – stuartd Jun 30 '17 at 19:05
  • I'm a bit confused, I just want to have a fix value for the SetGateways 192.168.1.254 because I used the user defined function on the `button_click` – EnnT Jul 01 '17 at 14:22

0 Answers0