I'm trying to implement some functionality that downloads a file from a URL. However, if the file is taking longer than 30 seconds, I'd like to cancel the download, or have it time out.
I've tried overriding the WebClient class to implement a timeout, but no matter what value I set the timeout to, it never times out! Here is the code I've tried, found in another stackoverflow answer:
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;
}
}
Then, called using:
WebDownload webClient = new WebDownload(20000);
try
{
webClient.DownloadFile(url, tmpFile);
}
catch {
//throw error
}
I've also tried using the WebRequest method to download the file, and using the Timeout and ReadWriteTimeout properties, but no dice. This has to be a pretty common use case. Any help is appreciated. Thanks!