2013-02-16 73 views

回答

14

您可以使用NetworkInformation class来检测;此示例代码添加了每当连接状态发生更改时都会调用的事件处理程序;

NetworkInformation.NetworkStatusChanged += 
    NetworkInformation_NetworkStatusChanged; // Listen to connectivity changes 

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

    if (profile.GetNetworkConnectivityLevel() >= 
       NetworkConnectivityLevel.InternetAccess) 
    { 
     // We have Internet, all is golden 
    } 
} 

当然,如果你想只检测一次,而不是收到通知时,它的变化,你可以做检查从上面不听变化事件。

+0

完美,谢谢 – gurehbgui 2013-02-16 09:20:45

+0

另外请注意,你可以得到相当多的先进与此检测网络状态:http://msdn.microsoft .com/en-us/library/windows/apps/hh700376和这里列出的ConstrainedInternetAccess可能会提供一些访问级别:http://msdn.microsoft.com/en-us/library/windows/apps/windows .networking.connectivity.networkconnectivitylevel – 2013-02-17 23:30:12

+1

配置文件可以为null如果没有连接可用,所以必须检查它... – 2015-03-27 09:08:58

-3

只写了异步函数来做到这一点:

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 
     { 
     } 
    } 
+1

最糟糕的答案我见过很多时间花花公子...绝对是性能杀手... – 2015-03-26 16:22:06

+0

此外代码使用Ping类,这是Windows商店应用程序无法使用的问题。 – Mog0 2015-08-16 22:42:05

1
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 2014-04-13 04:42:38