C#检查Internet连接 [英] C# checking Internet connection

查看:146
本文介绍了C#检查Internet连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我,如果有一种方法来检查,如果在我的电脑的互联网连接时,我的C#程序正在运行。举个简单的例子,如果互联网是工作,我将输出一个消息框,说接入互联网。否则我会输出一个消息说,互联网是不可用

Can you please tell me if there is a way to check if there is a internet connection in my computer when my C# program is running. For a simple example, if internet is working, I would output a message box saying Internet is available. else I would output a message saying, Internet is unavailable.

如果不使用库函数,看看网络可用时(因为这不检查互联网连接)

Without using the library function to see if network is available (since this doesn't check internet connectivity)

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

或者不打开一个网页,看它是否回归数据

Or without opening a webpage and seeing if it's return data

using (WebClient client = new WebClient())
      htmlCode = client.DownloadString("http://google.com");

由于这两种以上方法不适合我的需要。

Because both of these above methods don't suit my needs.

推荐答案

短一些的版本:

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
}

您可以找到一个更广泛的讨论<一个href=\"http://stackoverflow.com/questions/2031824/what-is-the-best-way-to-check-for-internet-connectivity-using-net\">here

You can find a broader discussion here

这篇关于C#检查Internet连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆