Reputation: 2378
I'm writing a program in Visual Studio 2010 using C# .Net
The program is to save the file from a given url to local drive, with a custom timeout to save time.
Say the url is http://mywebsite.com/file1.pdf
, and I want to save the file to the directory C:\downloadFiles\
Currently, I'm using WebClient
.
WebClient.DownloadFile("http://mywebsite.com/file1.pdf", "C:\downloadFiles\file1.pdf");
I am able to save the file, but I ran into some problem.
Sometimes, the url just won't respond, so I have my program try to download 5 times before terminating. I then realize the default timeout for WebClient is too long for my need (like 2 min or something) Is there a simple way to set timeout shorter, say like 15 sec?
I also looked into HttpWebRequest
, which I can easily set the timeout HttpWebRequest.Timeout = 15000;
. However, with this method, I have no idea how I can download/save the file.
So my over all questions is: Which is more simple, setting timeout for WebClient
, or saving file using HttpWebRequest
? And how would I go about doing so?
Upvotes: 5
Views: 15433
Reputation: 9943
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 could 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);
}
}
Upvotes: 0
Reputation: 3100
You could 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's an example that get's a json
response in LinqPad: http://share.linqpad.net/aaeeum.linq
Upvotes: 6
Reputation: 3395
There's no direct way to change timeout with a WebClient
. But you can use WebClient.DownloadFileAsync()
instead. This will allow you to use CancelAsync()
when needed.
Upvotes: 1
Reputation: 35373
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;
}
}
Upvotes: 13