以编程方式断开网络连接

有没有办法以编程方式临时断开.NET 4.0中的网络连接?

我知道通过这样做我可以获得当前的网络连接状态……

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() 

但出于测试目的,我想测试我的应用程序丢失网络连接时的行为(没有物理拔出网络电缆)。

谢谢,克里斯。

你可以用WMI做到这一点。 这是我们用来禁用物理适配器来测试这些类型的场景。

 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()) { if ((string) item["NetConnectionId"] != "Local Area Connection") continue; using (item) { item.InvokeMethod("Disable", null); } } } } } } 

您没有指明操作系统,但这适用于Windows 7和Windows 8。

请注意 ,您需要成为管理员才能运行此function。

如果您使用“托管Wifi API”,则只需删除个人资料即可。 这对我有用。

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

如果需要重新连接到该网络,请务必保存xml配置文件:

 string xmlString = m_WlanInterface.GetProfileXml(ConnectionProfileString) 

然后你可以重复使用它

  m_WlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, xmlString, true); m_WlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, ConnectionProfileString);