如何确定 Windows 商店应用程序中是否有 Internet 连接?
问问题
8829 次
3 回答
14
您可以使用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
}
}
当然,如果您只想检测一次而不是在它更改时收到通知,您可以从上面进行检查,而无需监听 change 事件。
于 2013-02-16T08:59:44.290 回答
2
using Windows.Networking.Connectivity;
public static bool IsInternetConnected()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
bool internet = (connections != null) &&
(connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
return internet;
}
于 2014-04-13T04:23:33.077 回答
-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
{
}
}
于 2014-02-15T09:46:50.267 回答