以下代码有效,但是我想知道创建的MemoryStream
是否正确关闭。应该如何执行此操作,或者FileStreamResult
为我处理它?
public FileStreamResult DownloadBudgetedRoleOpportunities(
Guid projectGuid,
IEnumerable<Guid> guidRequiredRoles)
{
var rolebroker = new ProjectRoleBudgetBroker();
var memstream = rolebroker.CreateBudgetedRoleOpportunies(
projectGuid,
guidRequiredRoles);
var fsr = new FileStreamResult ( memstream, "application/csv" )
{
FileDownloadName = "RoleOpportunities.csv"
};
// memstream.Close(); throws exception
return fsr;
}
最佳答案
FileStreamResult
将为您做到这一点。如有疑问,请始终检查代码,因为代码永远不会说谎,并且由于ASP.NET MVC是开源的,因此查看代码更加容易。
在Google上快速搜索FileStreamResult.cs,可让您验证WriteFile
方法中的流是否已使用using
语句正确处理。 (无双关语)
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);
}
}
}