我的问题类似于这个问题: Does File() In asp.net mvc close the stream?
我在C#MVC 4中有以下内容。
FileStream fs = new FileStream(pathToFileOnDisk, FileMode.Open);
FileStreamResult fsResult = new FileStreamResult(fs, "Text");
return fsResult;
fs
会自动关闭FileStreamResult
吗?谢谢!
答案 0 :(得分:30)
是。它在流周围使用using
块,确保资源将被处置。
以下是FileStreamResult
WriteFile方法的内部实现:
protected override void WriteFile(HttpResponseBase response)
{
Stream outputStream = response.OutputStream;
using (this.FileStream)
{
byte[] buffer = new byte[0x1000];
while (true)
{
int count = this.FileStream.Read(buffer, 0, 0x1000);
if (count == 0)
{
return;
}
outputStream.Write(buffer, 0, count);
}
}
}