你有没有办法告诉我是否有办法在我的C#程序运行时检查我的电脑中是否有互联网连接.举一个简单的例子,如果互联网工作,我会输出一个消息框说Internet is available
.否则我会输出一条消息说,Internet is unavailable
.
不使用库函数来查看网络是否可用(因为这不检查互联网连接)
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
或者不打开网页并查看它是否返回数据
using (WebClient client = new WebClient()) htmlCode = client.DownloadString("http://google.com");
因为上述两种方法都不适合我的需要.
更短的版本:
public static bool CheckForInternetConnection() { try { using (var client = new WebClient()) using (var stream = client.OpenRead("http://www.google.com")) { return true; } } catch { return false; } }
另一种选择是:
Ping myPing = new Ping(); String host = "google.com"; byte[] buffer = new byte[32]; int timeout = 1000; PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(host, timeout, buffer, pingOptions); if (reply.Status == IPStatus.Success) { // presumably online }
你可以在这里找到更广泛的讨论
请考虑以下代码段...
Ping myPing = new Ping(); String host = "google.com"; byte[] buffer = new byte[32]; int timeout = 1000; PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(host, timeout, buffer, pingOptions); if (reply.Status == IPStatus.Success) { // presumably online }
祝好运!