Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading file from url with timeout

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?

like image 200
sora0419 Avatar asked Dec 02 '22 22:12

sora0419


1 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;
    }
}
like image 103
I4V Avatar answered Dec 17 '22 11:12

I4V