Windows8 检测网络

在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的博客

posted @   BeyondBlog  阅读(577)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示