Reset Network Connections

.net, c#

Solution

After some searching and experimentation, I found this blog post: Disable/Enable Network Connections Under Vista

It is a much better approach.

The just of it, is to use a utility called `mgmtclassgen.exe` to generate a wrapper class around the WMI `Win32_NetworkAdapter` class. Use the following command in a developer command prompt at the folder of your choosing:

mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs

After you've generated `NetworkAdapter.cs` you can import it into a new project, add `System.Management.dll` to your project references, and use the following code to disable or enable an adapter of your choosing:

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

Also keep in mind, your program will have to be run as an administrator on any systems where UAC is enabled - to do this it is recommended to create an application manifest. You can do that by changing the `requestedExecutionLevel` entry in your manifest file to this:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Problem

What's the best way to reset network connections using C#/.NET? My company has several machines out with customers that connect by various means (3G, wifi, ethernet cable) and sometimes (especially with 3G) are reporting to Windows that they're still connected when they're not. I have a way to check if the connection is really live, but I'm struggling to reset them. Here's one problem: ``` var searcher = new ManagementObjectSearcher("select * from Win32_NetworkAdapter"); var managementObject = searcher.Get(); foreach (ManagementObject obj in managementObject) { var name = obj.Properties["Name"].Value.ToString(); Console.WriteLine(name); obj.InvokeMethod("Disable", null); obj.InvokeMethod("Enable", null); } ``` As you can see, that will go through ALL network adapters and reset them, which I don't want to do. Furthermore, some adapters won't accept the null parameter. I can get the NetworkInterface objects I want with this: ``` var interfaces = NetworkInterface.GetAllNetworkInterfaces().Where(ni => ni.IsReceiveOnly == false && ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback); ``` But the NetworkInterface class seems to have no Start(), Stop(), Reset() etc methods. Where do I go from here?

Original source

Related problems