ASP.NET - Download file to client browser



Cheat sheet to Download file to the client browser

using System.IO;
    'FilePath - Refers to Full Path of the file
        protected void DownloadFile(string FilePath)
        {
            // Gets the File Name
            string fileName = FilePath.Substring(FilePath.LastIndexOf('\\') + 1);
            byte[] buffer;

            using (FileStream fileStream = new FileStream(FilePath, FileMode.Open))
            {
                int fileSize = (int)fileStream.Length;
                buffer = new byte[fileSize];
                // Read file into buffer
                fileStream.Read(buffer, 0, (int)fileSize);
            }
            Response.Clear();
            Response.Buffer = true;
            Response.BufferOutput = true;
            Response.ContentType = "application/x-download";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.CacheControl = "public";
            // writes buffer to OutputStream
            Response.OutputStream.Write(buffer, 0, buffer.Length);
            Response.End();
        }

Share |

 Cant find the page you are looking for?
 Help us to improve by adding the content that you are looking for.
 Leave a feedback
 We look forward to hear your comments and feedback.