简体   繁体   English

以编程方式断开网络连接

[英]Programmatically disconnect network connectivity

Is there a way to programmatically and temporarily disconnect network connectivity in .NET 4.0? 有没有办法以编程方式暂时断开.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. 谢谢,克里斯。

You could do it with WMI. 你可以用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. 您没有指明操作系统,但这适用于Windows 7和Windows 8。

Note that you will need to be an administrator for this to function. 请注意 ,您需要成为管理员才能运行此功能。

if you use 'Managed Wifi API' you can simply delete the profile. 如果您使用“托管Wifi API”,则只需删除个人资料即可。 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: 如果需要重新连接到该网络,请务必保存xml配置文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM