Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C# to enable a disabled wireless network card

I've got a problem where I need to enable a card that has been disabled already and a searcher on WMI NetworkAdapter does not return the object.

I can think of a possible way to do this but I've been unable to get it to work, thats is to create a managementObject using this as the constructor name. but this just throws exceptions

{\\.\root\CIMV2:Win32_NetworkAdapter.NetConnectionID='Wireless Network Connection'}

The other way was to shell a netsh and enable the device, which is kind of ugly, or to use shell32/dll "Enable" to do the same, again, both passing just the name. Ive been getting the name from a registry scan on HKLM\SYSTEM\CurrentControlSet\Network and looking for MediaType=2 to get a string list of wireless devices. All is good if I run the application while the adapter is enabled as I can get the networkObject for the wireless device but it all falls over if the application starts while the wireless device is disabled.

Thanks

Edit : This is the code that I would love to work but no go :(

using System;
using System.Management;
class Sample
{
    public static int Main(string[] args)
    {
        ManagementObject mObj = new ManagementObject("\\\\.\\root\\CIMV2:Win32_NetworkAdapter.NetConnectionID=\"Wireless Network Connection\"");
        mObj.InvokeMethod("Enable", null);
        return 0;
    }
}
like image 550
pedigree Avatar asked Apr 01 '13 20:04

pedigree


1 Answers

This method essentially is using C# to leverage the WMI and Win32_NetworkAdapter Class. It should have methods built in for:

  • Enable
  • Disable

So you can execute your command on a Selected interface.

You can achieve that in this manner:

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.Equals("Ethernet 802.3")) 
    {
        adapter.Disable();
    }
}

There is a blog that actually outlines such a task; it defines how to create a Wrapper around the WMI Class.

Another solution may be to also use the ControlService (advapi32).

[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool    ControlService(IntPtr hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus);

Hopefully that one of those ways help..

like image 128
Greg Avatar answered Nov 14 '22 23:11

Greg