ASP.Net C# Download Or Save Image File From URL
Posted by in CSharp May 10, 2011 11 Comments

This tutorial will show how to download a file (image,video,zip,pdf,doc,xls,ect) from a valid URL of a particular website then save it as a physical file on server disk. It provides one more solution when you want to copy/move a file from a server to another server.

I wrote a ASP.net page using C# for a demonstration. It assumes that you want to download a file from url: http://4rapiddev.com/wp-includes/images/logo.jpg then save it somewhere on your server:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
 
public partial class download_file_from_url : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = "http://4rapiddev.com/wp-includes/images/logo.jpg";
        string file_name = Server.MapPath(".") + "\\logo.jpg";
 
        save_file_from_url(file_name, url);
 
        Response.Write("The file has been saved at: " + file_name);
    }
 
    public void save_file_from_url(string file_name, string url)
    {
        byte[] content;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        WebResponse response = request.GetResponse();
 
        Stream stream = response.GetResponseStream();
 
        using (BinaryReader br = new BinaryReader(stream))
        {
            content = br.ReadBytes(500000);
            br.Close();
        }
        response.Close();
 
        FileStream fs = new FileStream(file_name, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        try
        {
            bw.Write(content);
        }
        finally
        {
            fs.Close();
            bw.Close();
        }
    }
}

Note: you need to using System.Net and System.IO namespace as line 7,8 to ensure some classes work properly.

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • mohammad

    I tried this code … its now working.. here is the exception details …

    System.InvalidCastException was unhandled by user code
    Message=Unable to cast object of type ‘System.Net.FileWebRequest’ to type ‘System.Net.HttpWebRequest’.
    Source=automaticDownloader

    • mohammad

      sorry .. I dont know why I had the problem … but i copied the hole code and it’s work fine
      sorry again and thanks

      • hoanhuynh

        Congrat mohammad!

        I think your external document may not available at that moment for some reasons. :)

  • http://www.edco.com Christopher

    I downloaded the project and placed it in a web server but when I browse to the page I get an error: Could not load type ‘download_file_from_url’.
    If I remove the Inherits=”download_file_from_url” section, then the page loads but does not download the image.

    I checked and the file the URL points to exists.

  • http://www.mrblackman.com mrblackman

    It’s working, thanks a lot…

  • http://www.book-marky.de favoriten verwalten

    I have been exploring for a little for any high-quality articles or weblog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i am satisfied to convey that I’ve a very just right uncanny feeling I discovered exactly what I needed. I such a lot certainly will make certain to don?t forget this site and give it a look regularly.

  • http://www.hobtechnologies.com Imtiaz

    how can we make file download system in zip, but not for any specific url, for e.g i have various file to download user can select any file that file start download please help thanks

  • Thebawoo

    Brilliant

  • Ahmad Hamid

    This will not work for large files … larger than 500000 bytes… you need to loop over the stream and read one chunk at a time and write it to the file.  

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);        WebResponse response = request.GetResponse();        Stream stream = response.GetResponseStream();        BinaryReader br = new BinaryReader(stream);        FileStream fs = new FileStream(file_name, FileMode.Create);        BinaryWriter bw = new BinaryWriter(fs);        int bufferSize = 32768;        int dataSize = 0;        do        {            byte[] content = br.ReadBytes(bufferSize);            dataSize = content.Length;            if (dataSize > 0)            {                bw.Write(content);                bw.Flush();                content = br.ReadBytes(bufferSize);                dataSize = content.Length;            }        } while (dataSize > 0);        br.Close();        bw.Close();         response.Close();

  • RJ

    how to get thumbnail image from uploaded video on youtube and image save in project folder