I'm writing a string to a MemoryStream
I need to return the stream to the Controller Action so I can send it off as a file for download.
Normally, I wrap the Stream in a using statement, but, in this case, I need to return it. Does it still get Disposed after I return it? Or do I need to dispose it myself somehow?
//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 the 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?
}
According to source code here aspnet/AspNetWebStack/blob/master/src/System.Web.Mvc/FileStreamResult.cs
Yes
Where
FileStream
would have been the stream passed when you calledUpdate.
Your question was originally tagged as Asp.Net MVC but the code looks like the more recent core framework.
Found it there as well though written differently it does the same thing technically.
aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs