2012-10-19 37 views
0

任何人都知道一個很好的方式來查看用戶是否在線/離線?當我使用公共靜態布爾IsConnectedToNetwork();並看看它是假的/真的似乎永遠是真實的,即使當我關閉我的互聯網來測試它...IsConnectedToNetwork for Windows8 WinRT失敗

我錯過了什麼嗎?現在

public static bool nets() 
{ 
    bool go = 
     System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); 

    if (go == false) 
    { 
     return false; 
    } 
    return true; 
} 

,在我啓動我運行:

var ba = nets(); 

if (ba == false) 
{ 
    txtHeader.Text = "err"; 
} 
if (ba != false) 
{ 
    // Code 
} 

我也試過:

public static bool IsConnectedToNetwork(); 
+0

我相信,如果網絡適配器連接到網絡IsConnectedToNetwork()返回true,*不*如果你有互聯網連接。 –

+0

我實際上已經嘗試過這個......它回來是一個誤報。如果你看看我的更新代碼,你會明白我的意思...... – user1667125

+0

你看過網絡狀態改變的示例(http://code.msdn.microsoft.com/windowsapps/Network-Information-Sample-63aaa201/查看/源碼#內容)?它有代碼來做你正在問什麼(幷包括互聯網與本地網絡連接) –

回答

0

你可以ping通的幾個衆所周知的一個URL來看看你響應。

+0

說實話,我找不到任何包括「Ping」(使用Windows.Networking.Connectivity, 使用系統.Net.NetworkInformation,或 使用Windows.Networking.Sockets)... – user1667125

+0

我認爲他的意思是一般在做一個web請求bing.com,看看會發生什麼 –

+0

是的,這就是我的意思。 –

2

我用

public static bool IsConnectedToInternet() 
{ 
    ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile(); 
    return (connectionProfile!=null && connectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess); 

} 
+0

似乎不喜歡我......我試圖看看它是否爲空,並告訴我我不能使用「==」運算符。 – user1667125

+0

你爲什麼測試null?只需將此方法複製到您的代碼並調用它即可 –

0

我有一個似乎工作相當不錯,尤其是注意到有時可能以太網似乎是在使用中,即使它不是在Windows 8 RTM ...這就是爲什麼似乎沒有任何辦法工作!

但是,這樣做的以下是我測試一個不錯的選擇

var profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile(); 

     var interfaceType = profile.NetworkAdapter.IanaInterfaceType; 
      // 71 is WiFi & 6 is Ethernet 
      if (interfaceType == 71 | interfaceType == 6) 
      { 
       // Run Code 
      } 
      /* 3G/Mobile Detect 
      else if (interfaceType == 243 | interfaceType == 244) 
      { 
       // Run Code if you need to use a less quality feature. 
      }*/ 
      else 
      { 
       txtHeader.Text = "Error, Check connection or Try connecting to the Internet..."; 
      }