我有一个网站,用户可以在其中下载文件。有些文件非常大(最大的是 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/