在Windows8 上检测网络很简单用到
NetworkInformation这个类
可以看到这个类里面有以下几个方法和事件
public static event NetworkStatusChangedEventHandler NetworkStatusChanged;//网络连接改变的事件 public static IReadOnlyList<ConnectionProfile> GetConnectionProfiles(); public static IReadOnlyList<HostName> GetHostNames();//获取Host GetInternetConnectionProfile()//详细网络配置 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的博客