I'm looking for a way to to enable or disable DHCP using C# on a given network adapter. looking for the easiest solution.
Thank you.
I'm looking for a way to to enable or disable DHCP using C# on a given network adapter. looking for the easiest solution.
Thank you.
Maybe..
const string networcCardName = "[00000007] Intel(R) Ethernet Connection I217-LM"; //Example NIC name
var management = new ManagementClass("Win32_NetworkAdapterConfiguration");
var moc = management.GetInstances();
foreach (var o in moc)
{
var mo = (ManagementObject) o;
if (!(bool) mo["IPEnabled"]) continue;
if (!mo["Caption"].Equals(networcCardName)) continue;
var ndns = mo.GetMethodParameters("SetDNSServerSearchOrder");
ndns["DNSServerSearchOrder"] = null;
var enableDhcp = mo.InvokeMethod("EnableDHCP", null, null);
var setDns = mo.InvokeMethod("SetDNSServerSearchOrder", ndns, null);
}
You could use Process
to fire off netsh commands to set all the properties in the network dialogs.
eg: To set a static ipaddress on an adapter
netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0 192.168.0.1 1
To set it to dhcp you'd use
netsh interface ip set address "Local Area Connection" dhcp
To do it from C# would be
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface ip set address \"Local Area Connection\" static 192.168.0.10 255.255.255.0 192.168.0.1 1");
p.StartInfo = psi;
p.Start();
Setting to static can take a good couple of seconds to complete so if you need to, make sure you wait for the process to exit.