Set timeout for webClient.DownloadFile()

UnkwnTech picture UnkwnTech · Mar 2, 2009 · Viewed 104.6k times · Source

I'm using webClient.DownloadFile() to download a file can I set a timeout for this so that it won't take so long if it can't access the file?

Answer

Beniamin picture Beniamin · Jun 16, 2010

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

using System;
using System.Net;

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}

and you can use it just like the base WebClient class.