首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用.NET、C#和WPF检查互联网连接

如何使用.NET、C#和WPF检查互联网连接
EN

Stack Overflow用户
提问于 2011-03-23 21:24:48
回答 6查看 41.8K关注 0票数 23

我正在使用.NET,C#和WPF,我需要检查连接是否打开到某个网址,我无法获得任何我在互联网上找到的代码。

我试过了:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    IAsyncResult result = socket.BeginConnect("localhost/myfolder/", 80, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(3000, true);
    if (!success)
    {
        MessageBox.Show("Web Service is down!");
    }
    else
        MessageBox.Show("Everything seems ok");
}
finally
{
    socket.Close();
}

但是,即使我关闭了本地Apache服务器,我也总是收到一切正常的消息。

我也试过了:

ing ping = new Ping();
PingReply reply;
try
{
    reply = ping.Send("localhost/myfolder/");
    if (reply.Status != IPStatus.Success)
        MessageBox.Show("The Internet connection is down!");
    else
        MessageBox.Show("Seems OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error: " + ex.Message);
}

但这总是会给出一个异常(ping似乎只对服务器执行ping操作,所以localhost可以工作,但localhost/myfolder/不能)

请告诉我如何检查连接才能为我工作?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-03-23 22:37:57

最后,我使用了自己的代码:

private bool CheckConnection(String URL)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Timeout = 5000;
        request.Credentials = CredentialCache.DefaultNetworkCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
            return true;
        else
            return false;
    }
    catch
    {
        return false;
    }
}

有趣的是,当服务器关闭时(我关闭了我的Apache),我不会得到任何HTTP状态,但是会抛出一个异常。但这已经足够好用了:)

票数 23
EN

Stack Overflow用户

发布于 2013-06-27 14:02:06

你可以试试这个;

private bool CheckNet()
{
    bool stats;
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
    {
        stats = true;
    }
    else
    {
        stats = false;
    }
    return stats;
}
票数 14
EN

Stack Overflow用户

发布于 2011-03-23 21:51:37

使用以下命令:

private bool CheckConnection()
{
    WebClient client = new WebClient();
    try
    {
        using (client.OpenRead("http://www.google.com"))
        {
        }
        return true;
    }
    catch (WebException)
    {
        return false;
    }
}
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5405895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档