Download file with url with timeout

I am writing a program in Visual Studio 2010 using C # .Net

The program is designed to save a file from a given URL on a local disk with a user timeout in order to save time.

Say the url is http://mywebsite.com/file1.pdf and I want to save the file in the directory C:\downloadFiles\

I am currently using WebClient .

 WebClient.DownloadFile("http://mywebsite.com/file1.pdf", "C:\downloadFiles\file1.pdf"); 

I can save the file, but I had a problem.

Sometimes the URL just won't respond, so I have a program that you try to download 5 times before exiting. Then I understand that the default timeout for WebClient is too long for my need (e.g. 2 minutes or something else). Is there an easy way to set a timeout shorter, for example 15 seconds?

I also looked through the HttpWebRequest , which I can easily set the timeout to HttpWebRequest.Timeout = 15000; . However, with this method, I have no idea how I can upload / save a file.

So, on all issues:. Which is easier, set a timeout for WebClient or save the file using HttpWebRequest ? And how would I do that?

+4
source share
4 answers

You can create your own webclient

 public class MyWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { var req = base.GetWebRequest(address); req.Timeout = 15000; return req; } } 
+10
source

You can use the HttpClient class if you are using .NET 4.5:

 using(var httpClient = new HttpClient()) { httpClient.Timeout = new TimeSpan(0, 0, 15); Stream response = await httpClient.GetStreamAsync("http://mywebsite.com/file1.pdf"); ... } 

Here is an example that gets json response in LinqPad: http://share.linqpad.net/aaeeum.linq

+4
source

There is no direct way to change the timeout using WebClient . But instead, you can use WebClient.DownloadFileAsync() . This will allow you to use CancelAsync() if necessary.

+1
source

In .net 4 and above you can do something like

 var wreq = WebRequest.Create("http://mywebsite.com/file1.pdf"); wreq.Timeout = 15000; var wresp = (HttpWebResponse)request.GetResponse(); using (Stream file = File.OpenWrite("path/to/output/file.pdf")) { wresp.GetResponseStream().CopyTo(file); // CopyTo extension only .net 4.0+ } 

Otherwise, you can copy it yourself

 using (Stream file = File.OpenWrite("path/to/output/file.pdf")) { var input = wresp.GetResponseStream(); var buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, len); } } 
0
source

Source: https://habr.com/ru/post/1488740/


All Articles