Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does FileStreamResult close Stream?

My question is similar to this question: Does File() In asp.net mvc close the stream?

I have the follows in C# MVC 4.

FileStream fs = new FileStream(pathToFileOnDisk, FileMode.Open); FileStreamResult fsResult = new FileStreamResult(fs, "Text"); return fsResult; 

Will fs be closed automatically by FileStreamResult? thanks!

like image 687
totoro Avatar asked Oct 09 '14 10:10

totoro


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!

How do I return a stream file?

To return a file stream, you can use a FileStreamResult. This lets you specify the stream, the MIME type, and some other options (like the file name). // the stream when the transfer is complete.


1 Answers

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

Here is the internal implementation of the FileStreamResult WriteFile method:

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 143
Faris Zacina Avatar answered Sep 22 '22 02:09

Faris Zacina