ASP.NET - Download File with C#

I have seen many code snippets showing how to download a file and save to local disk with C#. Some of them are pretty long. But since the release of ASP.NET 2.0, downloading file is really a matter of one line of code. Here is an example:

/* Author: Abu Haider */
/* Dec 2009 */
/* Downloading and saving a file to local disk */
/* www.haiders.net */

new System.Net.WebClient().DownloadFile("http://example.com/file.zip", "c:\downloads\myfile.zip");
/* And thats all */

The WebClient class has several handy Methods for downloading resources from the Web. The DownloadFile Method takes only two arguments, the Uri of the file to download, and the FileName where to save the file. If the file already exists, it will be overwritten without any warning!

The code sample above is not specific to ASP.NET, you can use it in Console applications or WinForms applications as well.

Since the FileName parameter expects complete local path, in an ASP.NET Website you may have to translate a relative path to a complete file system path with Server.MapPath().

/* Author: Abu Haider */
/* Dec 2009 */
/* Downloading and saving a file to local disk */
/* To be used in an ASP.NET Page */
/* www.haiders.net */

string url = "http://example.com/file.zip";
string fileName = Server.MapPath("~/downloads/file.zip");
new System.Net.WebClient().DownloadFile(url, fileName);

Another handy function on the WebClient is DownloadString(Uri). It downloads the target Web Page and returns it as a String.

Posted on December 18, 2009 05:24 by Haider

Comments

December 22. 2009 04:40

J Marshall

That is so simple! I guess knowing what is already built into the .net Framework can save a lot of time.

J Marshall

Don't Post SPAM

If you are posting a commment just to get a link, don't waste your time!

I have a sophisticated comment moderation system in place, and your comment will not be posted.

Add comment




biuquote
  • Comment
  • Preview
Loading