views:

2724

answers:

4

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?

+2  A: 

As far as I know, you can't set timeout on webClient. I'd rather use HttpWebrequest instead.

Axarydax
+5  A: 

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

abatishchev
A: 

Have you tried to do this?

using (var oWebClient = new WebClient())
{
  oWebClient.Headers.Add(HttpRequestHeader.KeepAlive, Data.Environment.TtlServerRest);
  result = oWebClient.DownloadFile(param, param);
}

This worked for me using DownloadString method.

jaloplo
But this has nothing to do with the question? This adds a Keep-Alive header to the HTTP request. The questionner wants to be able to specify a timeout, so that if the file download takes too long, his code aborts it.
MarkJ
+3  A: 

My answer comes from here

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

public class WebDownload : WebClient
{
    private int _timeout;
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout
    {
        get
        {
            return _timeout;
        }
        set
        {
            _timeout = value;
        }
    }

    public WebDownload()
    {
        this._timeout = 60000;
    }

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

    protected override WebRequest GetWebRequest(Uri address)
    {
        var result = base.GetWebRequest(address);
        result.Timeout = this._timeout;
        return result;
    }
}

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

zrytane