Code for Downloading a file in asp.net and C#
If you want to download a file which is in your project folder.step 1: Create a new web page and Name it as DownloadFile.aspx
step 2 : Add this below code in Code behind file (.cs ) file
#region Namespace
using System;
using System.IO;
#endregion
#region Description , Methods and Functions
///
///
/// Summary description for DownloadFile.aspx
///
/// ************************************************************
/// * Project Name : Pricing Point (Wells Fargo) *
/// * Created on : Monday, June 28 2010 *
/// * Page Name : DownloadFile.aspx *
/// * Procedure name : sp_DashboardDetails *
/// * Front end : Visual Studio 2010 *
/// * Back end : Sql server 2008 *
/// * Framework version : 4.0 *
/// ************************************************************
///
///
///
public partial class DownloadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.Get("Id") != null)
{
string strRequest = Request.QueryString.Get("Id");
//-- if something was passed to the file querystring
//get absolute path of the file
if (!string.IsNullOrEmpty(strRequest))
{
string path = Server.MapPath(strRequest);
//get file object as FileInfo
System.IO.FileInfo file = new System.IO.FileInfo(path);
//-- if the file exists on the server
//set appropriate headers
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
//if file does not exist
}
else
{
Response.Write("This file does not exist.");
}
//nothing in the URL as HTTP GET
}
else
{
Response.Write("Please provide a file to download.");
}
}
}
}
#endregion
step 3: Call this function in where you have requirement for downloading file
Pass file Name to this function
Response.Redirect("~/DownloadFile.aspx?Id=" + filename);
No comments:
Post a Comment