Set timeout for webClient.DownloadFile()


Question

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?

1
90
4/23/2011 8:17:39 AM

Accepted Answer

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

41
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
Icon