ASP.NETダウンロードファイル

1119 ワード

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();
        }