在Windows8 上檢測網路很簡單用到
NetworkInformation這個類
可以看到這個類裡面有以下幾個方法和事件
public static event NetworkStatusChangedEventHandler NetworkStatusChanged;//網路連接改變的事件public static IReadOnlyList<ConnectionProfile> GetConnectionProfiles();public static IReadOnlyList<HostName> GetHostNames();//擷取HostGetInternetConnectionProfile()//詳細網路設定GetConnectionProfiles()//網路概要資訊
var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp != null && icp.NetworkAdapter != null) { var hostname = NetworkInformation.GetHostNames().SingleOrDefault( hn => hn.IPInformation != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); System.Diagnostics.Debug.WriteLine("可用網路IP:" + hostname.DisplayName); System.Diagnostics.Debug.WriteLine("網路狀態:" + icp.GetNetworkConnectivityLevel()); }
使用
NetworkInformation.GetInternetConnectionProfile();擷取網路設定後可以得到 NetworkAdapter 網路裝置
GetNetworkConnectivityLevel()得到當前網路的狀態 他是一個枚舉類型具體如下
// Summary: // No connectivity. 沒有訪問 None = 0, // // Summary: // Local network access only. 本網訪問 LocalAccess = 1, // // Summary: // Limited internet access. This value indicates captive portal connectivity, // where local access to a web portal is provided, but access to the Internet // requires that specific credentials are provided via the portal. This level // of connectivity is generally encountered when using connections hosted in // public locations (e.g. coffee shops and book stores). // 有限的訪問 ConstrainedInternetAccess = 2, // // Summary: // Local and Internet access. internet訪問 InternetAccess = 3,
可以用NetworkInformation裡面的 NetworkStatusChanged 監聽網路改變然後在做相應的處理
歡迎轉載,轉載請註明來自BeyondBlog的部落格