如何在Windows商店应用程序中确定是否有互联网连接?
NetworkInformation
类来检测这个;此示例代码添加一个事件处理程序,每次连接状态更改时都会调用它。NetworkInformation.NetworkStatusChanged +=
NetworkInformation_NetworkStatusChanged; // Listen to connectivity changes
static void NetworkInformation_NetworkStatusChanged(object sender)
{
ConnectionProfile profile =
NetworkInformation.GetInternetConnectionProfile();
if ((profile != null) && profile.GetNetworkConnectivityLevel() >=
NetworkConnectivityLevel.InternetAccess)
{
// We have Internet, all is golden
}
}
当然,如果你只想检测一次,而不是在改变时得到通知,那么你可以在不监听更改事件的情况下从上方进行检查。using Windows.Networking.Connectivity;
public static bool IsInternetConnected()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
bool internet = (connections != null) &&
(connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
return internet;
}
刚刚编写了异步函数来完成这个任务:
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
{
}
}