以下代码工作,但我想知道是否正确关闭创建的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 for 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,_bufferSize); if (bytesRead == 0) { // no more data break; } outputStream.Write(buffer,bytesRead); } } }