我想通过控制器ActionResult返回大文件,并已实现像下面的自定义FileResult类。FileResult缓冲到内存
public class StreamedFileResult : FileResult
{
private string _FilePath;
public StreamedFileResult(string filePath, string contentType)
: base(contentType)
{
_FilePath = filePath;
}
protected override void WriteFile(System.Web.HttpResponseBase response)
{
using (FileStream fs = new FileStream(_FilePath, FileMode.Open, FileAccess.Read))
{
int bufferLength = 65536;
byte[] buffer = new byte[bufferLength];
int bytesRead = 0;
while (true)
{
bytesRead = fs.Read(buffer, 0, bufferLength);
if (bytesRead == 0)
{
break;
}
response.OutputStream.Write(buffer, 0, bytesRead);
}
}
}
}
但是,我遇到的问题是整个文件似乎被缓冲到内存中。我需要做什么来防止这种情况发生?
为什么不使用现有的FileStreamResult? –
我最初尝试使用FileStreamResult,但它也将文件缓冲到内存中。 –