如何确定互联网连接是否可用?

9
如何在Windows商店应用程序中确定是否有互联网连接?
3个回答

15
您可以使用NetworkInformation来检测这个;此示例代码添加一个事件处理程序,每次连接状态更改时都会调用它。
NetworkInformation.NetworkStatusChanged += 
    NetworkInformation_NetworkStatusChanged; // Listen to connectivity changes

static void NetworkInformation_NetworkStatusChanged(object sender)
{
    ConnectionProfile profile = 
        NetworkInformation.GetInternetConnectionProfile();

    if ((profile != null) && profile.GetNetworkConnectivityLevel() >=
                NetworkConnectivityLevel.InternetAccess)
    {
        // We have Internet, all is golden
    }
}
当然,如果你只想检测一次,而不是在改变时得到通知,那么你可以在不监听更改事件的情况下从上方进行检查。

还要注意,您可以在检测网络状态方面变得更加高级:http://msdn.microsoft.com/en-us/library/windows/apps/hh700376,并且此处列出的ConstrainedInternetAccess可能会提供“某些”访问级别:http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkconnectivitylevel - Adam Tuliper
1
正如@Cabuxa.Mapache所指出的那样,这个答案没有检查profile != null,这在每次连接不可用时都会发生。 - Filipe Madureira

2
using Windows.Networking.Connectivity;      

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

1
考虑为您的代码添加一些上下文,以解释为什么您的答案回答了 OP 的问题。 - mdewitt

-5

刚刚编写了异步函数来完成这个任务:

    private void myPingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        if (e.Cancelled)
            return;

        if (e.Error != null)
            return;

        if (e.Reply.Status == IPStatus.Success)
        {
            //ok connected to internet, do something
        }
    }

    private void checkInternet()
    {
        Ping myPing = new Ping();
        myPing.PingCompleted += new PingCompletedEventHandler(myPingCompletedCallback);
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions options = new PingOptions(64, true);
        try
        {
            myPing.SendAsync("google.com", timeout, buffer, options);
        }
        catch
        {
        }
    }

2
这是我见过的最糟糕的答案之一,兄弟...绝对会影响性能... - Cabuxa.Mapache
此外,该代码使用了 Ping 类,而该类在 Windows Store 应用程序中不可用,而问题正是关于这个。 - Mog0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接