Download a file in an aspx page

Simple code to download a file from the server
internal static class AspxHelper
{
///
/// Renders the file to the users Browser by specifying the file as a filestream
///

/// The user s page
/// The file report as a filestream.
/// Collection of paths of files to download
internal static void DownloadFile(System.Web.UI.Page pg, string _downloadpath)
{


FileStream fileReportStream = null;
try
{
fileReportStream = File.OpenRead(_downloadpath);
byte[] Buffer = new byte[fileReportStream.Length];
fileReportStream.Read(Buffer, 0, Buffer.Length);

string fileName = _downloadpath;
if (fileName.Contains("\\"))
{
fileName = fileName.Substring(fileName.LastIndexOf("\\")+1);
}
pg.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);

switch (new System.IO.FileInfo(_downloadpath).Extension.ToUpper())
{
case Constants.Extensions.PDF:
pg.Response.ContentType = "application/pdf";
break;
case Constants.Extensions.WORD:
pg.Response.ContentType = "application/msword";
break;
case Constants.Extensions.ACCESS:
pg.Response.ContentType = "application/vnd.ms-access";
break;
case Constants.Extensions.XML:
pg.Response.ContentType = "application/xml";
break;
case Constants.Extensions.ZIP:
pg.Response.ContentType = "application/zip";
break;
default:
break;
}

pg.Response.BinaryWrite(Buffer);
pg.Response.Flush();
pg.Response.Close();
pg.Response.End();


}
catch (Exception)
{
throw;
}
finally
{
if (fileReportStream != null)
{
fileReportStream.Close();
}
}
}
}

0 comments:

Post a Comment