我正在使用下面的方法来检查 c# 中的互联网连接是否可用
我正在使用它使用 .NET 检查 Internet 连接的最佳方法是什么? https://stackoverflow.com/questions/2031824/what-is-the-best-way-to-check-for-internet-connectivity-using-net
public static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://www.google.com"))
{
return true;
}
}
catch
{
return false;
}
}
上面的方法有效,但我遇到了问题,有时需要很长时间才能重新运行值,可能是互联网速度,但是当我在网络浏览器中打开 Google.com 时,链接会在一秒钟内打开,那么为什么需要时间才能获取C# 的结果
您可以这样检查互联网是否可用:
ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile == null)
{
//logic ....
}
if (internetConnectionProfile != null)
{
this.IsInternetAvailable = internetConnectionProfile.GetNetworkConnectivityLevel() ==
NetworkConnectivityLevel.InternetAccess;
if (internetConnectionProfile.NetworkAdapter.IanaInterfaceType != 71)// Connection is not a Wi-Fi connection.
{
var isRoaming = internetConnectionProfile.GetConnectionCost().Roaming;
//user is Low on Data package only send low data.
var isLowOnData = internetConnectionProfile.GetConnectionCost().ApproachingDataLimit;
//User is over limit do not send data
var isOverDataLimit = internetConnectionProfile.GetConnectionCost().OverDataLimit;
IsWifiConnected = true;
}
else //Connection is a Wi-Fi connection. Data restrictions are not necessary.
{
IsWifiConnected = true;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)