c# 下载文件封装方法

一,普通下载(大文件会报内存错)

/// <summary>
        /// 普通下载
        /// </summary>
        /// <param name="FileName">文件虚拟路径</param>
        ///  /// <param name="name">返回客户端名称</param>
        public static void DownLoadold(string FileName, string name)
        {
            string destFileName = FileName;
            if (System.IO.File.Exists(destFileName))
            {
                try
                {
                    FileInfo fi = new FileInfo(destFileName);
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ClearHeaders();
                    HttpContext.Current.Response.Buffer = false;
                    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
                    HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    HttpContext.Current.Response.WriteFile(destFileName);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                   
                }
                catch { }
                finally
                {
                    HttpContext.Current.Response.Close();
                    GC.Collect();
                }
            }
        }

二,分块下载

 /// <summary>
        /// 分块下载
        /// </summary>
        /// <param name="FileName">文件虚拟路径</param>
       /// <param name="name">文件虚拟路径</param>
        public static void DownLoad(string FileName, string name)
        {
            string filePath = FileName;
            long chunkSize = 204800;             //指定块大小 
            byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区 
            long dataToRead = 0;                 //已读的字节数   
            FileStream stream = null;
            try
            {
                //打开文件   
                stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                dataToRead = stream.Length;

                //添加Http头   
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));//HttpUtility.UrlEncode(Path.GetFileName(filePath))
                HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

                while (dataToRead > 0)
                {
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.Clear();
                        dataToRead -= length;
                    }
                    else
                    {
                        dataToRead = -1; //防止client失去连接 
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error:" + ex.Message);
            }
            finally
            {
                if (stream != null) stream.Close();
                HttpContext.Current.Response.Close();
            }
        }

或者

public static void download(string fileName, string filePath)
{
   System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
   if (fileInfo.Exists == true)
   {
     const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
     byte[] buffer = new byte[ChunkSize];
     Response.Clear();
     System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
     long dataLengthToRead = iStream.Length;//获取下载的文件总大小
     Response.ContentType = "application/octet-stream";
     Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
     while (dataLengthToRead > 0 && Response.IsClientConnected)
      {
          int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
          Response.OutputStream.Write(buffer, 0, lengthRead);
          Response.Flush();
         dataLengthToRead = dataLengthToRead - lengthRead;
      }
      Response.Close();
   }
}
 
原文地址:https://www.cnblogs.com/qingjiawen/p/14684574.html