Search code examples
c#timeoutwebrequest

Retry on The operation has timed out or The connection was closed unexpectedly


I would like to retry only those download attempts that have failed and likely not reached destination server set. Retrying other failed attempts as well would be only waste of time due to incrementing nonce with each request.

This is my simplified download method that would probably work as described:

public string Download(string url)
{
    bool retried = false;
    retry:
    try
    {
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        using (StreamReader reader = new StreamReader(webrequest.GetResponse().GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
    catch (WebException e)
    {
        if (e.Message == "The operation has timed out" || e.Message == "The connection was closed unexpectedly")
        {
            if (!retried)
            {
                retried = true;
                goto retry;
            }
        }
    }
    return "";
}

problem is that e.Message is localizated. Thus, I would have to use if (e.Message == "language 1" || e.Message == "language 2" || e.Message == "language 3" || ...).

Is there any more elegant way to retry only on The operation has timed out or The connection was closed unexpectedly? Or to retry only on requests that have likely not reached destination server yet in general? Thanks!


Solution

  • Check if:

    e.Status == WebExceptionStatus.Timeout || e.Status == WebExceptionStatus.KeepAliveFailure
    

    You can see all the WebExceptionStatus values here