2

I am using below method to check internet connection available or not in c# and I was using it from What is the best way to check for Internet connectivity using .NET?

 public static bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead("http://www.google.com"))
            {
                return true;
            }
        }
        catch
        {
            return false;
        }
    }

above method works but I am facing problem, some time it takes a long time to rerun value, may be internet speed, but when I open Google.com in web browser then link open in a second, so why it is taking time to get result from C#

Community
  • 1
  • 1
Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77
  • Probably google determines you as bot, and delays response? – Uriil Feb 16 '15 at 09:14
  • Try setting the `WebClient`s Proxy property to null – Bridge Feb 16 '15 at 09:15
  • possible duplicate of [C# WebClient acting slow the first time](http://stackoverflow.com/questions/4932541/c-sharp-webclient-acting-slow-the-first-time) – Sinatr Feb 16 '15 at 09:15
  • Possible duplicate of [How do I check for a network connection?](https://stackoverflow.com/questions/520347/how-do-i-check-for-a-network-connection) – T.Todua Sep 09 '19 at 11:11

3 Answers3

2

You can check whether internet is available or not like this:

ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
            if (internetConnectionProfile == null)
            {
               //logic ....
            }

            if (internetConnectionProfile != null)
            {
                this.IsInternetAvailable = internetConnectionProfile.GetNetworkConnectivityLevel() ==
                                           NetworkConnectivityLevel.InternetAccess;

                if (internetConnectionProfile.NetworkAdapter.IanaInterfaceType != 71)// Connection is not a Wi-Fi connection. 
                {
                    var isRoaming = internetConnectionProfile.GetConnectionCost().Roaming;

                    //user is Low on Data package only send low data.
                    var isLowOnData = internetConnectionProfile.GetConnectionCost().ApproachingDataLimit;

                    //User is over limit do not send data
                    var isOverDataLimit = internetConnectionProfile.GetConnectionCost().OverDataLimit;
                    IsWifiConnected = true;

                }
                else //Connection is a Wi-Fi connection. Data restrictions are not necessary. 
                {
                    IsWifiConnected = true;

                }
            }
Bridge
  • 29,818
  • 9
  • 60
  • 82
MMM
  • 3,132
  • 3
  • 20
  • 32
  • Although this would be my preferred method of checking the internet connection, it has to be said that this is only supported from Windows 8 and upwards. More details: [MSDN](https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkinformation.getinternetconnectionprofile) – Bernd Linde Feb 16 '15 at 09:38
0

I think your TimeOut is not working because of Domain Name Resolution. I you are proxy behind you must configure it on app.config file.

Check that example, I hope it helps you. I did it using .Net 4.0.

    static bool CheckForInternetConnection(int timeOut = 3000)
    {
        var task = CheckForInternetConnectionTask(timeOut);

        return task.Wait(timeOut) && task.Result;
    }

    static Task<bool> CheckForInternetConnectionTask(int timeOut = 3000)
    {
        return Task.Factory.StartNew
            (() =>
            {
                try
                {
                    var client = (HttpWebRequest) WebRequest.Create("http://google.com/");
                    client.Method = "HEAD";
                    client.Timeout = timeOut;

                    using (var response = client.GetResponse())
                    using (response.GetResponseStream())
                    {
                        return true;
                    }
                }
                catch
                {
                    return false;
                }
            });
    }

And a sample call:

Console.WriteLine("CheckForInternetConnection -> {0}", CheckForInternetConnection());

If you are proxy behind, do not forget to add proxy configuration on app.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <defaultProxy  enabled="true">
      <proxy proxyaddress="http://127.0.0.1:1111" usesystemdefault="True"/>
    </defaultProxy>
  </system.net>
</configuration>
denys-vega
  • 3,522
  • 1
  • 19
  • 24
-1
public static bool ConnectionTest()
    {
        try
        {
            string site = "http://www.google.com/";
            TcpClient client = TcpClient(site, 80);
            client.Close();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

Something like this should be faster.