.net - 下载二进制文件的更好方法

标签 .net binary download

我有一个网站,用户可以在其中下载文件。有些文件非常大(最大的是 323 MB)。当我测试它以尝试下载此文件时,出现内存不足异常。我知道下载文件的唯一方法如下。我使用下面的代码的原因是 URL 已编码,我不能让用户直接链接到文件。有没有另一种方法可以下载这个文件而不必将整个文件读入字节数组?

  FileStream fs = new FileStream(context.Server.MapPath(url),
                                 FileMode.Open,
                                 FileAccess.Read);

  BinaryReader br = new BinaryReader(fs);
  long numBytes = new FileInfo(context.Server.MapPath(url)).Length;
  byte[] bytes = br.ReadBytes((int) numBytes);

  string filename = Path.GetFileName(url);
  context.Response.Buffer = true;
  context.Response.Charset = "";

  context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  context.Response.ContentType = "application/x-rar-compressed";
  context.Response.AddHeader("content-disposition", "attachment;filename=" + filename);

  context.Response.BinaryWrite(bytes);
  context.Response.Flush();
  context.Response.End();

最佳答案

代替

context.Response.BinaryWrite(bytes);


context.Response.TransmitFile(context.Server.MapPath(url));

这将避免将整个文件读入内存。

关于.net - 下载二进制文件的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1512342/

相关文章:

没有链接的 JavaScript blob 文件名

c# - 如何检查泛型类型参数是否可为空?

.net - Windows UI 自动化无法识别按钮控件

java - 计算 Java 中的前导零 (clz) 或前导零 (nlz) 的数量

Java递归二分查找抛出越界异常?

performance - 快速模 3 或除法算法?

javascript - 如何使用 javascript 下载此文件?

php - 如何查看我的服务器的上传和下载速度?

c# - .NET Custom UserControl 的内容在调整父级大小时消失

.net - 在 Mac 上通过 dotnet cli 使用 f#