tags:

views:

43

answers:

3

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.

+3  A: 

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.

Remus Rusanu
+1  A: 

Just use WebClient.DownloadFile (or WebClient.DownloadFileAsync if you don't want to freeze the UI during the download)

Thomas Levesque
+1  A: 

Since you have gigantic files, prepare for some kind of connection recovery.

Whatever method you will find out to get something from the http (WebClient, TcpStream, ...) you should probably code with recovery in mind from the start. That should be focus here.

For that, it would be imperative to check if Stream returned from GetResponseStream() supports Seek().

Daniel Mošmondor