Set timeout for webClient.DownloadFile()


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?

4/23/2011 8:17:39 AM

Accepted Answer

Try WebClient.DownloadFileAsync(). You can call CancelAsync() by timer with your own timeout.

3/2/2009 10:39:22 AM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow