簡體   English   中英

在C#中檢查互聯網連接是否可用

[英]check internet connection available or not in c#

我正在使用下面的方法來檢查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;
        }
    }

上面的方法有效,但是我遇到了問題,有時需要很長時間才能重新運行值,這可能是互聯網速度,但是當我在網絡瀏覽器中打開Goog​​le.com並在一秒鍾內打開鏈接時,為什么要花一些時間才能獲得來自C#的結果

您可以像這樣檢查互聯網是否可用:

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

這樣的事情應該更快。

我認為您的超時由於域名解析而無法正常工作。 我是代理,您必須在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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM