从WinRT获取互联网连接状态

本文关键字:连接 状态 互联网 获取 WinRT | 更新日期: 2023-09-27 17:51:20

下面的代码我已经使用了一段时间来获取我的商店应用程序运行的设备的连接状态。最近发生的事情是,虽然它仍然找到正确的连接配置文件,但它返回级别为Local,而不是Internet access。

IReadOnlyList<ConnectionProfile> p = NetworkInformation.GetConnectionProfiles();
foreach (ConnectionProfile prof in p)
{
    NetworkConnectivityLevel lev = prof.GetNetworkConnectivityLevel();
    if (lev == NetworkConnectivityLevel.InternetAccess)
    {
        return true;
    }
}
return false;

谁能告诉我为什么这可能是,我怎么能说服它,我做,事实上,有一个工作的互联网连接(我可以证明能够张贴这个问题:-))?

从WinRT获取互联网连接状态

试试这个

private bool roaming;
    private string connectionProfileInfo;
    private async Task<bool> IsConnectedToInternet()
    {
        HttpWebRequest webReq;
        HttpWebResponse resp = null;
       // HttpStatusCode respcode;
        Uri url = null;
        url = new Uri("http://www.dartinnovations.com");
        webReq = (HttpWebRequest)WebRequest.Create(url);
        try
        {
            resp = (HttpWebResponse)await webReq.GetResponseAsync();
          //  Debug.WriteLine(resp.StatusCode);
            webReq.Abort();
            webReq = null;
            url = null;
            resp = null;
            return true;
        }
        catch
        {
            webReq.Abort();
            webReq = null;
            return false;
        }
    }
    private async Task<bool> CheckForConnection()
    {
        bool isConnected = await IsConnectedToInternet();
        Debug.WriteLine(isConnected);
        ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

        if (isConnected)
        {
            if (internetConnectionProfile != null)//Gets metereing info, Connectionprofile gives false positives when used to check for internet connectivity
            {
                Debug.WriteLine("internet available");
                GetMeteringInformation(internetConnCectionProfile);
            }
            else
            {
                connectionProfileInfo = "Roaming information not available";
                roaming = false;
               // Debug.WriteLine("no connections");
            }
            return true;
        }           
        return false;
    }
  private async Task GetMeteringInformation(ConnectionProfile connectionProfile)
    {
        ConnectionCost connectionCost = connectionProfile.GetConnectionCost();
        roaming = connectionCost.Roaming;
        connectionProfileInfo = "Over Data Limit :" + connectionCost.OverDataLimit + " | Approaching Data Limit :" +
                                connectionCost.ApproachingDataLimit;
    }