Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With FileStreamResult, how is the MemoryStream closed?

The following code works, but I'm wondering if the MemoryStream created is closed properly. How should this be performed or does FileStreamResult handle it for me?

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; } 
like image 844
kenny Avatar asked May 02 '12 17:05

kenny


People also ask

Does FileStreamResult close the stream?

Yes. It uses a using block around the stream, and that ensures that the resource will dispose. thanks!

Does MemoryStream need to be disposed?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.


1 Answers

The FileStreamResult will do that for you. When in doubt always check the code, because the code never lies and since ASP.NET MVC is open source it's even more easy to view the code.

A quick search on Google for FileStreamResult.cs lets you verify that in the WriteFile method the stream is correctly disposed using the using statement. (no pun intended)

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);         }     } } 
like image 115
João Angelo Avatar answered Oct 28 '22 14:10

João Angelo