Set timeout for webClient.DownloadFile()
Solution 1:
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.
Solution 2:
Try WebClient.DownloadFileAsync()
. You can call CancelAsync()
by timer with your own timeout.
Solution 3:
Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.