检查Webclient是否连接到远程服务器

时间:2015-06-13 08:41:27

标签: c# asp.net

我想检查我的项目是否可以通过ASP.NET C#中的Webclient连接到远程服务器并执行某些操作。

这是我的代码

WebClient webClient = new WebClient();
webClient.Credentials = new System.Net.NetworkCredential(username, password);

if (webClient.OpenRead(url83).IsConnected) // Here, i want to check
{
    XmlTextReader reader1 = new XmlTextReader(webClient.OpenRead(url83));
    reader1.WhitespaceHandling = WhitespaceHandling.None;
    //Do something
}

1 个答案:

答案 0 :(得分:0)

如上所述here检查互联网连接的最佳方式可能类似于

try
{
    using (var client = new WebClient())
    using (var stream = client.OpenRead(url83))
    {
        XmlTextReader reader1 = new XmlTextReader(stream);
        reader1.WhitespaceHandling = WhitespaceHandling.None;
        //Do something
    }
}
catch (WebException ex)
{
     // occurs when any error occur while reading from network stream
}