What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2426
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

27条回答
  •  庸人自扰
    2020-11-22 08:24

    public static bool Isconnected = false;
    
    public static bool CheckForInternetConnection()
    {
        try
        {
            Ping myPing = new Ping();
            String host = "google.com";
            byte[] buffer = new byte[32];
            int timeout = 1000;
            PingOptions pingOptions = new PingOptions();
            PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
            if (reply.Status == IPStatus.Success)
            {
                return true;
            }
            else if (reply.Status == IPStatus.TimedOut)
            {
                return Isconnected;
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }
    
    public static void CheckConnection()
    {
        if (CheckForInternetConnection())
        {
            Isconnected = true;
        }
        else
        {
            Isconnected = false;
        }
    }
    

提交回复
热议问题