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
2009-03-02 10:39:15
+5
A:
Try WebClient.DownloadFileAsync()
. You can call CancelAsync()
by timer with your own timeout.
abatishchev
2009-03-02 10:39:22
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
2010-02-03 12:16:02
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
2010-03-23 15:39:00
+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
2010-06-16 10:57:13