C# 判断电脑是否联网

项目中连接webAPI需要判断是否联网,故找到这个方法,不需要引用任何dll,代码复制一下,直接使用。wininet.dll是系统自带的

   public  void Initial()
        {
            try
            {               
                if (IsNetworkConnected)
                {
                    SvMaster.Log.WriteInfo("网络连接成功");
                }
                else
                {
                    SvMaster.Log.WriteError("网络连接失败,请检查网络!");
                }
            }
            catch (Exception ex)
            {
                SvMaster.Log.WriteError(ex);
            }
        }      
        [DllImport("wininet.dll", EntryPoint = "InternetGetConnectedState")]
        public extern static bool InternetGetConnectedState(out int conState, int reader);

        public static bool IsNetworkConnected
        {
            get
            {
                return InternetGetConnectedState(out int n, 0);
            }
        }

说明:该方法亲测可用,记录。

猜你喜欢

转载自blog.csdn.net/qq_42711010/article/details/140953917