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!
Yes. It uses a using block around the stream, and that ensures that the resource will dispose. thanks!
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.
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); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With