检查c#中是否提供互联网连接

时间:2015-02-16 09:10:57

标签: c#

我使用以下方法检查c#中是否有可用的互联网连接 我在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;
        }
    }

以上方法有效,但我遇到问题,有时需要很长时间才能重新运行价值,可能是互联网速度,但是当我在网络浏览器中打开Goog​​le.com然后在一秒钟内打开链接,那么为什么要采取是时候从C#获得结果了

3 个答案:

答案 0 :(得分:2)

您可以检查互联网是否可用:

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;

                }
            }

答案 1 :(得分:0)

public static bool ConnectionTest()
    {
        try
        {
            string site = "http://www.google.com/";
            TcpClient client = TcpClient(site, 80);
            client.Close();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

这样的事情应该更快。

答案 2 :(得分:0)

我认为您的TimeOut因域名解析而无效。我是你的代理,你必须在app.config文件上配置它。

检查一下这个例子,希望对你有帮助。我是用.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;
                }
            });
    }

示例电话:

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

如果您是代理人,请不要忘记在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>