title: C# - How to set static IP address to USB to Ethernet adapter?
body: <p>I have a C# application in which I need to detect a USB to Ethernet adapter connected to a PC and set it with a static IP address. The adapter can be of any brand, I don't know which one the end user will have. All I do know is that it will be only one USB to Ethernet adapter connected to that PC.</p>
  
  <p>Here is my current code which should have worked:</p>
  
  <pre><code>public static bool SetStaticIPAddress(out string exception)
  {
      const string USBtoEthernetAdapter = "USB to Ethernet Adapter";
  
      var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
      var networkCollection = adapterConfig.GetInstances();
      foreach (ManagementObject adapter in networkCollection)
      {
          string description = adapter["Description"] as string;
  
          if (description.StartsWith(USBtoEthernetAdapter, StringComparison.InvariantCultureIgnoreCase))
          {
              try
              {
                  var newAddress = adapter.GetMethodParameters("EnableStatic");
                  newAddress["IPAddress"] = new string[] { "10.0.0.2"};
                  newAddress["SubnetMask"] = new string[] { "255.255.255.0"};
  
                  adapter.InvokeMethod("EnableStatic", newAddress, null);
                  exception = null;
                  return true;
              }
              catch (Exception ex)
              {
                  exception = $"Unable to Set IP: {ex.Message}";
                  return false;
              }
          }
      }
      exception = $"Could not find any \"{USBtoEthernetAdapter}\" device connected";
      return false;
  }
  </code></pre>
  
  <p>But, unfortunately , it doesn't and when I run <code>ipconfig</code> the IP is not set to 10.0.0.2 and this makes other parts of my app that tries to <code>ping</code> it to fail...</p>
  
  <p>When I debug the code I see that it does find a <code>ManagementObject</code> with the description "USB to Ethernet Adapter" but its IP doesn't change.</p>
  
  <p>I searched the web and found on MSDN this code sample that uses <code>NetworkInterface</code> so I tried this:</p>
  
  <pre><code>NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
  foreach (NetworkInterface adapter in adapters)
  {
      IPInterfaceProperties properties = adapter.GetIPProperties();
      // This is the name of the USB adapter but I can't relay on this name
      // since I don't know which device the user will use except for the fact
      // that is will be a USB to Ethernet Adapter...
      if (adapter.Description == "Realtek USB FE Family Controller")
      {
          // No way to set the device IP here...
      }
  }
  </code></pre>
  
  <p>Is there a 100% way to detect that single USB adapter and set it with the static IP?</p>