c# HttpWebRequest IOException
<p>I am using the following function to navigate to URL addresses in my c# winform code. </p>

<p>I think, the code is fine but when it tries to make connection to the URL address, it fails and throws a <em>IOException Error</em>:</p>

<p>My Question is: </p>

<p><strong>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?</strong></p>

<pre><code>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 &gt; 0);
                    stream.Close();
                }
                catch (WebException ex)
                {

                }


            }


            return sb.ToString();
        }
</code></pre>

<p>Thanks friends for all of your answers. They are all correct. However, I finally found my error and corrected it. </p>

<p>The problem is I was trying to catch WebException , however, the error I was getting IOException. </p>

<p>I changed WebException as IOException and corrected my code as following:</p>

<pre><code>catch (IOException ex)
                    {
                       System.Threading.Thread.Sleep(500);                       
                       myReq = (HttpWebRequest)WebRequest.Create(url);
                       myReq.KeepAlive = false;
                    }
</code></pre>

<p>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.</p>

<p>Sorry for taking your time but you helped me in a great way and provided insight. Thanks!</p>
