以编程方式断开网络连接

10
有没有办法在.NET 4.0中以编程的方式暂时断开网络连接?
我知道可以通过以下方式获取当前网络连接状态...
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

但出于测试目的,我希望在应用程序失去网络连接时测试其行为(而不是物理上拔掉网络电缆)。

谢谢, Chris。


3
就是拔掉那个该死的东西。 :) - rfmodulator
2
是的,我知道我可以拔掉网络电缆。但正如我在问题中所说,我想通过编程方式断开网络连接,以帮助测试应用程序中的已连接和已断开功能。 - ChrisNel52
2个回答

18

你可以使用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<ManagementObject>())
                {
                    if ((string) item["NetConnectionId"] != "Local Area Connection")
                        continue;

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

您没有说明操作系统,但此方法适用于Windows 7和Windows 8。

请注意,您需要拥有管理员权限才能正常运行此方法。


我喜欢它。优雅、精确,而且你没有让我拔掉网络电缆 :-) - ChrisNel52
4
附注:该方法需要在Windows 7上拥有管理员权限(可能也适用于Windows 8和Windows Vista)。 - Karsten

1
如果您使用“Managed 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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接