Best way to programmatically configure network adapters in .NET

TimK picture TimK · Mar 27, 2009 · Viewed 35.7k times · Source

I have an application written in C# that needs to be able to configure the network adapters in Windows. I have this basically working through WMI, but there are a couple of things I don't like about that solution: sometimes the settings don't seem to stick, and when the network cable is not plugged in, errors are returned from the WMI methods, so I can't tell if they really succeeded or not.

I need to be able to configure all of the settings available through the network connections - Properties - TCP/IP screens.

What's the best way to do this?

Answer

PaulB picture PaulB · Apr 17, 2009

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.