Showing posts with label ASP.Net File download from server. Show all posts
Showing posts with label ASP.Net File download from server. Show all posts

Saturday, February 18, 2012

Create file download option using ASP.NET and C#


Create file download using ASP.Net
This post is for creation of download link using ASP.NET and C# Technology. A download link is very much necessary to create a typical web application.




Step 1) Copy and paste the below code in your ASP.Net page. Change the Directory location according to your server setting.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class File_download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        DirectoryInfo directory = new DirectoryInfo("D:\\files");
        int counter = 0;
        foreach (FileInfo file in directory.GetFiles())
        {
            HyperLink link = new HyperLink();
            link.ID = "Link" + counter++;
            link.Text = file.Name;
            link.NavigateUrl = "download.aspx?name=" + file.Name;

            Page.Controls.Add(link);
            Page.Controls.Add(new LiteralControl("<br/>"));
        }
    }
}


Step 2)Create another ASP.NET file and give filename download.aspx and put below code into it.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string fileName = Request.QueryString["name"].ToString();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        Response.TransmitFile("D:\\files\\" + fileName);
        Response.End();

    }
}