有很多方法可以检查Internet是否以C#连接到计算机。利用System.Net命名空间,该命名空间提供了向URI标识的资源发送数据和从中接收数据的通用方法。WebClient或HttpClient类提供了用于将数据发送到URI标识的任何本地,Intranet或Internet资源或从中接收数据的通用方法。在下面的示例中,我们使用(OpenRead)将资源中的数据作为流返回。
如果成功返回true或false,则点击URL“ http://google.com/generate_204”进行检查。
下面的示例在循环中运行,并检查是否已连接Internet。如果已连接Internet,则返回true,否则返回false。
static void Main(string[] args){
var keepRetrying = true;
while (keepRetrying){
if (IsConnectedToInternet()){
keepRetrying = false;
System.Console.WriteLine("Connected");
} else {
keepRetrying = true;
System.Console.WriteLine("Not Connected");
}
}
}
public static bool IsConnectedToInternet(){
try{
using (var client = new WebClient())
using (client.OpenRead("http://google.com/generate_204"))
return true;
}
catch { }
return false;
}输出结果
Connected