简体   繁体   English

在C#中检查互联网连接是否可用

[英]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? 我正在使用下面的方法来检查c#中的Internet连接是否可用,而我正在使用以下方法: 使用.NET检查Internet连接的最佳方法是什么?

 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# 上面的方法有效,但是我遇到了问题,有时需要很长时间才能重新运行值,这可能是互联网速度,但是当我在网络浏览器中打开Goog​​le.com并在一秒钟内打开链接时,为什么要花一些时间才能获得来自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. 我是代理,您必须在app.config文件中对其进行配置。

Check that example, I hope it helps you. 检查该示例,希望对您有所帮助。 I did it using .Net 4.0. 我使用.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. 如果您落后于代理,请不要忘记在app.config文件中添加代理配置。

<?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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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