I am using the following function to navigate to URL addresses in my c# winform code.
I think, the code is fine but when it tries to make connection to the URL address, it fails and throws a IOException Error:
My Question is:
How can I add a check in the code to make sure that connection to URL is successfully made and if it is not, than it will re-try until it makes a successful connection?
public String WebRequestNavigate(string url)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
if (url != "")
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = false;
try
{
HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();
Stream stream = resp.GetResponseStream();
String test = "";
int count = 0;
do
{
**count = stream.Read(buf, 0, buf.Length);**
if (count != 0)
{
test = Encoding.UTF8.GetString(buf, 0, count);
sb.Append(test);
}
}
while (count > 0);
stream.Close();
}
catch (WebException ex)
{
}
}
return sb.ToString();
}
Thanks friends for all of your answers. They are all correct. However, I finally found my error and corrected it.
The problem is I was trying to catch WebException , however, the error I was getting IOException.
I changed WebException as IOException and corrected my code as following:
catch (IOException ex)
{
System.Threading.Thread.Sleep(500);
myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = false;
}
I used your suggestion for Thread.Sleep in order to make my code wait before attempting a new URL connection. This solved my problem %100.
Sorry for taking your time but you helped me in a great way and provided insight. Thanks!
Some thing similar but simpler: