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

mer*_*ert 17 c# microsoft-metro windows-8

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

Mar*_*han 41

我使用这个片段没有问题:

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

  • 如果存在多个连接,则这不起作用,例如在仿真器中可能是这种情况.使用下面的Joshua Heller代码来解决问题. (3认同)

Jos*_*ler 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;
    }
}
Run Code Online (Sandbox Code Playgroud)