C#判断计算机是否联网

方法一
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 | 引用: 0 | 查看次数: 4502
发表评论
登录后再发表评论!