Saturday, February 20, 2010

How to DownLoad a File in ASP.NET ?

To DownLoad a file:-

1. Add a link to page, Like this:-
               <a href="Download.ashx?FileName=file.pdf&FilePath=DownLoad/">Download Standing Order Mandate</a >

          Where file.pdf = file to download
                     DownLoad = Folder name where the file placed at server.

2. Then  Add a Generic Handler to the website/project with the name Download.ashx and add the following code:
   public void ProcessRequest(HttpContext context)
    {
        if (context.Request.QueryString["FileName"] != null && context.Request.QueryString["FilePath"] != null)
        {
            string strFileName = context.Request.QueryString["FileName"];
            string strOnPath = @"~/" + context.Request.QueryString["FilePath"].ToString() + strFileName;
            string strpath = context.Server.MapPath(strOnPath);
            FileInfo myFile = new FileInfo(strpath);
            context.Response.Clear();
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
            context.Response.AddHeader("Content-Length", myFile.Length.ToString());
            context.Response.ContentType = "application/octet-stream";
            context.Response.WriteFile(myFile.FullName);
            context.Response.End();
        }

  

No comments: