【问题标题】:Programmatically disconnect network connectivity以编程方式断开网络连接
【发布时间】:2012-01-04 21:08:57
【问题描述】:

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

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

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

但出于测试目的,我想测试我的应用程序在失去网络连接时的行为(无需物理拔下网络电缆)。

谢谢, 克里斯。

【问题讨论】:

  • 只要拔掉该死的东西。 :)
  • 是的,我知道我可以拔掉网线。但就像我在问题中所说的那样,我想以编程方式断开网络连接,以帮助测试应用程序中的连接和断开连接功能。

标签: c# .net unit-testing networking


【解决方案1】:

你可以用 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。

请注意,您需要成为管理员才能使用此功能。

【讨论】:

  • 我喜欢。优雅,精确,而且你没有告诉我拔掉我的网线:-)
  • 旁注:此方法需要 Windows 7(可能还包括 Windows 8 和 Windows Vista)的管理员权限
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2023-01-27
    • 1970-01-01
    • 2013-04-30
    • 2011-06-29
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多