C# 在c中检查internet连接是否可用#
我使用下面的方法来检查c中是否有可用的internet连接# 而我是从C# 在c中检查internet连接是否可用#,c#,C#,我使用下面的方法来检查c中是否有可用的internet连接# 而我是从 上述方法有效,但我面临的问题是,重新运行值可能需要很长时间,可能是互联网速度,但当我在web浏览器中打开Google.com,然后在一秒钟内链接打开时,为什么要花时间从C#获取结果?您可以像这样检查互联网是否可用: ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetIntern
上述方法有效,但我面临的问题是,重新运行值可能需要很长时间,可能是互联网速度,但当我在web浏览器中打开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;
}
}
类似这样的速度应该更快。我认为由于域名解析,您的超时无法正常工作。如果您是代理服务器,则必须在app.config文件中对其进行配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy enabled="true">
<proxy proxyaddress="http://127.0.0.1:1111" usesystemdefault="True"/>
</defaultProxy>
</system.net>
</configuration>
看看这个例子,我希望它能帮助你。我是用.NET4.0做的
static bool CheckForInternetConnection(int timeOut = 3000)
{
var task = CheckForInternetConnectionTask(timeOut);
return task.Wait(timeOut) && task.Result;
}
static Task<bool> CheckForInternetConnectionTask(int timeOut = 3000)
{
return Task.Factory.StartNew
(() =>
{
try
{
var client = (HttpWebRequest) WebRequest.Create("http://google.com/");
client.Method = "HEAD";
client.Timeout = timeOut;
using (var response = client.GetResponse())
using (response.GetResponseStream())
{
return true;
}
}
catch
{
return false;
}
});
}
如果您落后于代理,请不要忘记在app.config文件中添加代理配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy enabled="true">
<proxy proxyaddress="http://127.0.0.1:1111" usesystemdefault="True"/>
</defaultProxy>
</system.net>
</configuration>
可能google将您确定为机器人,并延迟响应?请尝试将WebClient
的Proxy属性设置为null可能重复的可能重复的。虽然这是我检查internet连接的首选方法,但必须指出,这仅在Windows 8及以上版本中受支持。更多详情:
Console.WriteLine("CheckForInternetConnection -> {0}", CheckForInternetConnection());
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy enabled="true">
<proxy proxyaddress="http://127.0.0.1:1111" usesystemdefault="True"/>
</defaultProxy>
</system.net>
</configuration>