Check internet connection (availability) in Window

2019-01-14 16:33发布

问题:

How to check internet connection availability in Windows 8,C# development ? I looked at MSDN but page has been deleted.

回答1:

I use this snippet without problems:

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


回答2:

I had to use GetConnectionProfiles() and GetInternetConnectionProfile() to make it work across all devices.

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


回答3:

For Windows Phone Following code may be usefull:

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