Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Enable / Disable Connection

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

like image 462
pistacchio Avatar asked Jun 16 '10 12:06

pistacchio


People also ask

How to Enable Disable wifi or internet connection Programmatically?

Go to the AndroidManifest. xml file and add two user-permissions: ACCESS_WIFI_STATE and CHANGE_WIFI_STATE. Below is the code for the AndroidManifest.

What is enable and disable mobile data in android programmatically?

For your find Information, unless you have a rooted phone I don't think you can enable and disable data programmatically because in order to do so we have to include MODIFY_PHONE_STATE permission which is only given to system or signature apps. setMobileDataEnabled() method is no longer callable via reflection.

How do I connect to a specific Wi Fi network in android programmatically?

First and foremost, add permissions in your manifest file. These 4 permissions are required to make changes in your device network connectivity. Setup configuration to connect one specific wifi using WifiConfiguration. WifiConfiguration config = new WifiConfiguration();


1 Answers

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();
     }
    }

like image 79
Tim Lloyd Avatar answered Oct 28 '22 22:10

Tim Lloyd