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

后端 未结 27 2330
感动是毒
感动是毒 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:25

    I am having issue on those method on my 3g Router/modem, because if internet is disconnected the router redirects the page to its response page, so you still get a steam and your code think there is internet. Apples (or others) have a hot-spot-dedection page which always returns a certain response. The following sample returns "Success" response. So you will be exactly sure you could connect the internet and get real response !

    public static bool CheckForInternetConnection()
    {
        try
        {       
            using (var webClient = new WebClient())
            using (var stream = webClient.OpenRead("http://captive.apple.com/hotspot-detect.html"))
            {
                if (stream != null)
                {
                    //return true;
                    stream.ReadTimeout = 1000;
                    using (var reader = new StreamReader(stream, Encoding.UTF8, false))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            if (line == "SuccessSuccess")
                            {
                                return true;
                            }
                            Console.WriteLine(line);
                        }
                    }
    
                }
                return false;
            }
        }
        catch
        {
    
        }
        return false;
    }
    

提交回复
热议问题