2013-02-16 77 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