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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With