Set timeout for webClient.DownloadFile()

C#.NetDownloadWebclient

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

A lot of people make use of using(...) for the WebClient. Yes, WebClient implements IDisposable but this can cause socket exhaustion if you do it in bulk: https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUnkwnTechView Question on Stackoverflow
Solution 1 - C#BeniaminView Answer on Stackoverflow
Solution 2 - C#abatishchevView Answer on Stackoverflow
Solution 3 - C#jeffrymorrisView Answer on Stackoverflow
Solution 4 - C#user2029101View Answer on Stackoverflow