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

+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 –

+1

使用可能な接続がない場合、プロファイルはnullになる可能性がありますので、チェックしてください... –

-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

私が今までに多く見た最悪の答え時間のおい...絶対にパフォーマンスの殺人者... –

+0

また、このコードではPingクラスを使用していますが、これはWindows Storeアプリケーションでは利用できません。 – Mog0

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

関連する問題