Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file from the web within a WinForm application

Tags:

c#

download

I'm writting a C# utility program that I need the ability to download and save a file from a URL.

I have the code working to obtain the URL from a web service call, however I'm having trouble finding a simple example of how to begin the download and save the data to a disk file.

Does anyone have a good example of this, or can provide me with an example?

Thanks!

EDIT - I should mention that these files will be 3 to 4 GB in size. So if there are special considerations for files of this size I would appreciate any advice.

like image 438
Richard West Avatar asked Dec 05 '25 07:12

Richard West


1 Answers

WebClient.DownloadData, the spec contains a small sample. It is arguably more efficient to use WebRequest.GetResponseStream and save the data chunk by chunk, but you'll have to properly prepare the WebRequest yourself.

Updated

If you have to download 3-4GB files then you must do much much more than what the .Net framework offers. WebClient is immedeatly out-of-the-question since it returns the content as one monolithic byte[]. Even presuming that your VAS (virtual address space) has the contigous 4GB to burn on these downloads, .Net cannot alocate anything larger than 2Gb (on x64 as well). So you must use streams, as in GetResponseStream().

Second you must implement HTTP range units in your request, as per HTTP/1.1 section 3.12. Your request must contain Content-Range headers to be able to resume intrerupted downloads. And of course, your target server will have to accept and recognize these headers, and perhaps respond with a prpoer accept-ranges, which few servers do.

You have your plate full, downloading 4Gb is anything but trivial.

like image 161
Remus Rusanu Avatar answered Dec 07 '25 20:12

Remus Rusanu