Is Stream called when a file is returned from an action?

I write a string to a MemoryStream , I need to return the stream to the controller action so that I can send it as a file to load.

I usually wrap Stream in a using statement, but in this case I need to return it. Will it be disposed of after I return it? Or should I somehow manage it myself?

 //inside CsvOutputFormatter public Stream GetStream(object genericObject) { var stream = new MemoryStream(); var writer = new StreamWriter(stream, Encoding.UTF8); writer.Write(_stringWriter.ToString()); writer.Flush(); stream.Position = 0; return stream; } 

Controller action that returns a file:

 [HttpGet] [Route("/Discussion/Export")] public IActionResult GetDataAsCsv() { var forums = _discussionService.GetForums(_userHelper.UserId); var csvFormatter = new CsvOutputFormatter(new CsvFormatterOptions()); var stream = csvFormatter.GetStream(forums); return File(stream, "application/octet-stream", "forums.csv"); //is the stream Disposed here automatically? } 
+14
source share
1 answer

According to the source code here, aspnet / AspNetWebStack / blob / master / src / System.Web.Mvc / FileStreamResult.cs

Yes

 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); } } } 

Where FileStream would be the stream passed on call

 return File(stream, "application/octet-stream", "forums.csv"); 

Update

Your question was originally tagged Asp.Net MVC, but the code looks like a newer basic structure.

Found him there, although it is written differently, technically he does the same.

ASPnet / AspNetCore / blob / host /SRC/Mvc/Mvc.Core/SRC/ Infrastructure /FileResultExecutorBase.cs

 protected static async Task WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, long rangeLength) { var outputStream = context.Response.Body; using (fileStream) { try { if (range == null) { await StreamCopyOperation.CopyToAsync(fileStream, outputStream, count: null, bufferSize: BufferSize, cancel: context.RequestAborted); } else { fileStream.Seek(range.From.Value, SeekOrigin.Begin); await StreamCopyOperation.CopyToAsync(fileStream, outputStream, rangeLength, BufferSize, context.RequestAborted); } } catch (OperationCanceledException) { // Don't throw this exception, it most likely caused by the client disconnecting. // However, if it was cancelled for any other reason we need to prevent empty responses. context.Abort(); } } } 
+16
source

Source: https://habr.com/ru/post/1264219/


All Articles