C# WMI settinig ip programaticaly


SUBMITTED BY: Guest

DATE: Nov. 24, 2014, 8:12 a.m.

FORMAT: Text only

SIZE: 2.4 kB

HITS: 1203

  1. public void SetStatic()
  2. {
  3. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  4. ManagementObjectCollection moc;
  5. try
  6. {
  7. moc = mc.GetInstances();
  8. foreach (ManagementObject mo in moc)
  9. {
  10. if ((bool)mo["ipEnabled"]) //is adapter enabled
  11. {
  12. if (mo["Caption"].Equals(Name)) //is this the adapter i am looking for
  13. {
  14. ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic"); //Enable static ip on the adapter
  15. ManagementBaseObject newGateway = mo.GetMethodParameters("SetGateways"); //Enable custom Gateway addreses
  16. ManagementBaseObject newDns = mo.GetMethodParameters("SetDNSServerSearchOrder");
  17. newGateway["DefaultIPGateway"] = gateways.ToArray(); //Set the gateways
  18. newGateway["GatewayCostMetric"] = new int[] { 1 }; //Set metric cost to 1
  19. newIP["IPAddress"] = ipAddresses.ToArray(); //Set the ip address of the adapter
  20. newIP["SubnetMask"] = subnets.ToArray(); //Set the subnets
  21. newDns["DNSServerSearchOrder"] = dnses.ToArray(); //Set the dnses
  22. //the following three statement do the actual work of telling the addaper what goes where
  23. ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
  24. ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGateway, null);
  25. ManagementBaseObject setDNS = mo.InvokeMethod("SetDNSServerSearchOrder", newDns, null);
  26. break;
  27. }//End if - is this the addapter i am looking for
  28. }//End if - is adapter enabled
  29. }//End foreach - loop through management objects
  30. }
  31. catch (Exception err)
  32. {
  33. throw new ApplicationException(err.Message + "\n" + err.StackTrace);
  34. }//End catch
  35. }//End SetStatic

comments powered by Disqus