天高地厚

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ASP.NET下载文件 .

Posted on 2013-01-31 08:56  天高地厚-GNU  阅读(131)  评论(0编辑  收藏  举报

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