Monday, December 29, 2014

Download a file from Asp.net C#

Download a file from Asp.net C#

How to download the file from the server using the asp.net c#

For sample purpose i used one .css file for download

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleTestingCodes
{
    public partial class DownloadingFiles : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //File Extension
            string Extension = ".css";
            //File Name
            string fileName = "Site";
            //File path Location
            //You can also use this like
            //string path = Server.MapPath("../TempSql/") + fileName + Extension;
            string path = Server.MapPath("~/Styles/") + fileName + Extension;
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + Extension);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/....";
                Response.WriteFile(Server.MapPath("~/Styles/") + fileName + Extension);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }
}


No comments:

Post a Comment