0

I want to check if my project can connect to the remote server by Webclient in ASP.NET C# and do something.

here is my code

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
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
JesseRich
  • 1
  • 1
  • 5
  • 1
    So you've shown some code (which calls `OpenRead` twice - probably a bad idea) - so what does it do, compared with what you want it to do? – Jon Skeet Jun 13 '15 at 08:45
  • I just only want to read XML from another site with USername and password – JesseRich Jun 13 '15 at 08:47
  • FYI, you should not use `new XmlTextReader()` or `new XmlTextWriter()`. They have been deprecated since .NET 2.0. Use `XmlReader.Create()` or `XmlWriter.Create()` instead. – John Saunders Jun 13 '15 at 23:47

1 Answers1

0

As described here best way to check internet connectivity might be something like

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
}
Community
  • 1
  • 1
Adnan Umer
  • 3,669
  • 2
  • 18
  • 38