2

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.

Karl-Henrik
  • 1,113
  • 1
  • 11
  • 17
Mike
  • 1,122
  • 2
  • 13
  • 25

2 Answers2

6

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);
        }
Marcus
  • 8,230
  • 11
  • 61
  • 88
  • Thanks also a good option, voted for other due to its simplicity in understanding the code. – Mike May 21 '14 at 11:58
3

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.

PaulB
  • 23,264
  • 14
  • 56
  • 75