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

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

    I have three tests for an Internet connection.

    • Reference System.Net and System.Net.Sockets
    • Add the following test functions:

    Test 1

    public bool IsOnlineTest1()
    {
        try
        {
            IPHostEntry dummy = Dns.GetHostEntry("https://www.google.com");
            return true;
        }
        catch (SocketException ex)
        {
            return false;
        }
    }
    

    Test 2

    public bool IsOnlineTest2()
    {
        try
        {
            IPHostEntry dummy = Dns.GetHostEntry("https://www.google.com");
            return true;
        }
        catch (SocketException ex)
        {
            return false;
        }
    }
    

    Test 3

    public bool IsOnlineTest3()
    {
        System.Net.WebRequest req = System.Net.WebRequest.Create("https://www.google.com");
        System.Net.WebResponse resp = default(System.Net.WebResponse);
        try
        {
            resp = req.GetResponse();
            resp.Close();
            req = null;
            return true;
        }
        catch (Exception ex)
        {
            req = null;
            return false;
        }
    }
    

    Performing the tests

    If you make a Dictionary of String and Boolean called CheckList, you can add the results of each test to CheckList.

    Now, recurse through each KeyValuePair using a for...each loop.

    If CheckList contains a Value of true, then you know there is an Internet connection.

提交回复
热议问题