How to change the timeout on a .NET WebClient object

Ryall picture Ryall · Nov 24, 2009 · Viewed 182.8k times · Source

I am trying to download a client's data to my local machine (programatically) and their webserver is very, very slow which is causing a timeout in my WebClient object.

Here is my code:

WebClient webClient = new WebClient();

webClient.Encoding = Encoding.UTF8;
webClient.DownloadFile(downloadUrl, downloadFile);

Is there a way to set an infinite timeout on this object? Or if not can anyone help me with an example on an alternate way to do this?

The URL works fine in a browser - it just takes about 3 minutes to show.

Answer

kisp picture kisp · Aug 9, 2011

You can extend the timeout: inherit the original WebClient class and override the webrequest getter to set your own timeout, like in the following example.

MyWebClient was a private class in my case:

private class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest w = base.GetWebRequest(uri);
        w.Timeout = 20 * 60 * 1000;
        return w;
    }
}