10

on Windows 7 I can enable and disable connections via the Network Connections Manager panel (in system settings).

How can I do this programmatically in C#? Thanks

1
  • Any particular reason, as you would obviously stop all traffic on the computer, interrupting downloads etc? Commented Jun 16, 2010 at 12:53

1 Answer 1

16

You can achieve this in C# by leveraging WMI and the Win32_NetworkAdapter WMI class. The Win32_NetworkAdapter class has Enable and Disable methods which can be executed on a selected network interface.

An example of usage can be found here:

http://blog.opennetcf.com/ncowburn/2008/06/24/HOWTODisableEnableNetworkConnectionsProgrammaticallyUnderVista.aspx

link not available, but archived at:

http://web.archive.org/web/20120615012706/http://blog.opennetcf.com/ncowburn/2008/06/24/HOWTODisableEnableNetworkConnectionsProgrammaticallyUnderVista.aspx

Briefly, steps to do this are:

  1. Generate a wrapper for the class from VS command prompt

    mgmtclassgen Win32_NetworkAdapter /L CS -p NetworkAdapter.cs
  2. Stepping through the adapters:

    SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2");
    ManagementObjectSearcher search = new ManagementObjectSearcher(query);
    foreach(ManagementObject result in search.Get()) {
     NetworkAdapter adapter = new NetworkAdapter(result);
     // Identify the adapter you wish to disable here. 
     // In particular, check the AdapterType and 
     // Description properties.
     // Here, we're selecting the LAN adapters.
     if (adapter.AdapterType.Contains("Ethernet 802.3")) {
        adapter.Disable();
     }
    }

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do this using WMI query ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.