简体   繁体   中英

check internet connection available or not in c#

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#

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;

                }
            }
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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM