Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically disconnect network connectivity

Is there a way to programmatically and temporarily disconnect network connectivity in .NET 4.0?

I know I can get the current network connectivity status by doing this...

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

but for testing purposes I would like test my application's behavior when it loses network connectivity (without physically unplugging the network cable).

Thanks, Chris.

like image 453
ChrisNel52 Avatar asked Nov 23 '11 15:11

ChrisNel52


2 Answers

You could do it with WMI. Here's one we use for disabling the physical adapter to test these types of scenarios.

using System.Management;
using System.Linq;

namespace DisableNIC
{
    internal static class Program
    {
        private static void Main()
        {
            var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
                                            "WHERE NetConnectionId != null " +
                                              "AND Manufacturer != 'Microsoft' ");
            using (var searcher = new ManagementObjectSearcher(wmiQuery))
            {
                foreach (var item in searcher.Get().OfType<ManagementObject>())
                {
                    if ((string) item["NetConnectionId"] != "Local Area Connection")
                        continue;

                    using (item)
                    {
                        item.InvokeMethod("Disable", null);
                    }
                }
            }
        }
    }
}

You didn't indicate the OS, but this works in Windows 7 and Windows 8.

Note that you will need to be an administrator for this to function.

like image 173
Bob G Avatar answered Sep 22 '22 19:09

Bob G


if you use 'Managed Wifi API' you can simply delete the profile. That worked for me.

WlanClient client = new WlanClient();

WlanClient.WlanInterface m_WlanInterface = client.Interfaces.Where(i => i.InterfaceDescription.Contains(InterfaceIdentifierString)).First();
m_WlanInterface.DeleteProfile(ConnectionProfileString);

If you need to reconnect to that network, be sure to save the xml profile:

string xmlString = m_WlanInterface.GetProfileXml(ConnectionProfileString)

Then you can reuse it

 m_WlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, xmlString, true);
 m_WlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, ConnectionProfileString);
like image 1
Jay M Avatar answered Sep 20 '22 19:09

Jay M