在 Windows 8 中检查互联网连接(可用性)



如何在Windows 8,C#开发中检查互联网连接的可用性?我查看了MSDN,但页面已被删除。

我使用此代码段没有问题:

public static bool IsInternet()
{
    ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
    bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
    return internet;
}

我必须使用GetConnectionProfiles()和GetInternetConnectionProfile()才能使其在所有设备上工作。

class ConnectivityUtil
{
    internal static bool HasInternetConnection()
    {            
        var connections = NetworkInformation.GetConnectionProfiles().ToList();
        connections.Add(NetworkInformation.GetInternetConnectionProfile());
        foreach (var connection in connections)
        {
            if (connection == null)
                continue;
            if (connection.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
                return true;
        }
        return false;
    }
}

对于 Windows Phone,以下代码可能很有用:

var networkInformation = NetworkInformation.GetConnectionProfiles();    
if (networkInformation.Count == 0)    
{    
  //no network connection    
}          

最新更新