2011-11-23 86 views
10

有沒有辦法以編程方式暫時斷開.NET 4.0中的網絡連接?以編程方式斷開網絡連接

我知道我可以通過這樣獲得當前網絡的連接狀態...

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() 

但是出於測試目的,我想測試我的應用程序的行爲,當它失去網絡連接(無需物理拔掉網線)。

謝謝, 克里斯。

+3

只需拔下黨的事情。 :) – rfmodulator

+2

是的,我意識到我可以拔掉網線。但就像我在我的問題中所說的那樣,我想以編程方式斷開網絡,以幫助測試應用程序中連接和斷開的功能。 – ChrisNel52

回答

16

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

注意,你將需要爲這個管理員功能。

+0

我喜歡它。優雅,精確,你沒有告訴我要拔掉我的網線:-) – ChrisNel52

+3

備註:此方法需要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); 
相關問題