木子屋 Dnawo's BLOG

C#判断计算机是否联网

👤 dnawo 📅 2014-07-19 👁 5344 👍 0 💬 0 🔄 本站原创
方法一
public bool CheckForInternetConnection()
{
    bool result = false;

    try
    {
        Ping ping = new Ping();
        PingReply replay = ping.Send("114.114.114.114", 2000);
        if (replay.Status == IPStatus.Success)
        {
            result = true;
        }
    }
    catch { }

    return result;
}

方法二
public bool CheckForInternetConnection()
{
    bool result = false;

    try
    {
        using (WebClient client = new WebClient())
        {
            client.DownloadString("http://www.baidu.com/");
            result = true;
        }
    }
    catch { }

    return result;
}

说明:NetworkInterface.GetIsNetworkAvailable()仅用于检测是否有可用的网络连接(网卡),不能用于检测计算机是否联网。例如拨号上网的计算机,没有拨号时也是返回True。

参考资料

[1].C# checking Internet connection:http://stackoverflow.com/questions/20309158/c-sharp-checking-internet-connection
[2].How do I check for a network connection:http://stackoverflow.com/questions/520347/how-do-i-check-for-a-network-connection

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 WinForm调用主窗体Close方法失败:从不是创建控件的线程… 下一篇 → C#使用微软TTS语音引擎实现文字转语音示例