I'm a newcomer on .Net and c# programming. I'm trying to perform a small program to set up in a few clics the IP address of my local network card. (What I want to achieve is going faster than through the windows configuration menus) So I've made a little research and I found several nice examples that fits my needs. Anyway, I've realised that I can get a network device IP config via .Net namespaces (System.Net.Networkinformation...) but I can't set a new one (I mean, this API is full of getters but no setters) so, as far as I googled, to set an IP I must perform WMI calls. My question is if there is a method to do it via .Net (I didn't found it by de moment). Thanks in advance!
1 Answer
You can use ORMi library as it is a WMI wrapper that makes WMI access simpler.
1) Define your class:
[WMIClass("Win32_NetworkAdapterConfiguration")]
public class NetworkAdapterConfiguration
{
public int Index { get; set; } //YOU MUST SET THIS AS IT IS THE CIM_KEY OF THE CLASS
public string Caption { get; set; }
public string Description { get; set; }
public uint IPConnectionMetric { get; set; }
public UInt32 InterfaceIndex { get; set; }
public string WINSScopeID { get; set; }
public bool SetStatic(string ip, string netmask)
{
int retVal = WMIMethod.ExecuteMethod(this, new { IPAddress = new string[] { ip }, SubnetMask = new string[] { netmask } });
if (retVal != 0)
Console.WriteLine($"Failed to set network settings with error code {retVal}");
return retVal == 0;
}
}
2) Use:
WMIHelper helper = new WMIHelper("root\\CimV2");
NetworkAdapterConfiguration networkInterface = helper.Query<NetworkAdapterConfiguration>().ToList()
.Where(n => n.Description == "Intel(R) Ethernet Connection").SingleOrDefault();
networkInterface.SetStatic("192.168.0.35", "255.255.255.0");
1 Comment
B. McCartney
thanks for the code sample! Running on windows 10, SetStatic seems to be replaced with EnableStatic and instead of returning int, returns an object with ReturnValue property instead
System.Managementis part of the framework. If you don't like WMI, there's IPHelper, if you prefere API calls, or netsh, it you like the command line console-style better.