[英]Programmatically disconnect network connectivity
有沒有辦法以編程方式暫時斷開.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<ManagementObject>())
{
if ((string) item["NetConnectionId"] != "Local Area Connection")
continue;
using (item)
{
item.InvokeMethod("Disable", null);
}
}
}
}
}
}
您沒有指明操作系統,但這適用於Windows 7和Windows 8。
請注意 ,您需要成為管理員才能運行此功能。
如果您使用“托管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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.