如何判断Windows商店应用中是否有互联网连接?
答案 0 :(得分: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
}
}
当然,如果您只想检测一次而不是在更改时收到通知,您可以从上面进行检查,而不必听取更改事件。
答案 1 :(得分:1)
using Windows.Networking.Connectivity;
public static bool IsInternetConnected()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
bool internet = (connections != null) &&
(connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
return internet;
}
答案 2 :(得分:-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
{
}
}