我的问题类似于以下问题:
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
吗?谢谢! 最佳答案
是的。它在流周围使用using
块,并确保资源将被处置。
这是FileStreamResult
WriteFile方法的内部implementation:
protected override void WriteFile(HttpResponseBase response)
{
// grab chunks of data and write to the output stream
Stream outputStream = response.OutputStream;
using (FileStream)
{
byte[] buffer = new byte[BufferSize];
while (true)
{
int bytesRead = FileStream.Read(buffer, 0, BufferSize);
if (bytesRead == 0)
{
// no more data
break;
}
outputStream.Write(buffer, 0, bytesRead);
}
}
}