以编程方式断开网络连接 [英] Programmatically disconnect network connectivity

查看:291
本文介绍了以编程方式断开网络连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来在.NET 4.0中编程,并暂时断开网络连接?

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).

谢谢, 克里斯。

推荐答案

您可以使用WMI做到这一点。这里有一个我们使用禁用物理适配器,以测试这些类型的场景。

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

        var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
                                       "WHERE NetConnectionId != null " +
                                       "AND Manufacturer != 'Microsoft' ");
        using (var searcher = new ManagementObjectSearcher(wmiQuery))
        {
            foreach (ManagementObject item in searcher.Get())
            {
                if (((String)item["NetConnectionId"]) == "Local Area Connection")
                {
                    using (item)
                    {
                        item.InvokeMethod("Disable", null);
                    }
                }
            }
        }

您没有注明的操作系统,但是这适用于Windows 7。

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

这篇关于以编程方式断开网络连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆