检查Windows 8中的Internet连接(可用性)

时间:2012-11-29 11:56:30

标签: c# windows-8 microsoft-metro

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

3 个答案:

答案 0 :(得分:41)

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

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

答案 1 :(得分:10)

我必须使用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;
    }
}

答案 2 :(得分:0)

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

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