How do I create Csv in memory and return it to client?

Viewed 969

How do I create a csv-file in memory and return it as FileStreamResult? I tried to write to a memorystream and then return it with FileStreamResult but I always get the error ObjectDisposedException: Cannot access a closed Stream.. I tried setting leaveopen to true and disposing manually like told here but i still get the same error.

[HttpGet]
    public FileStreamResult GetData()
    {
        var myResult = DataGetter.GetData().ToList();
        using var memStream = new MemoryStream();
        var writer = new StreamWriter(memStream, Encoding.UTF8, 1024, true);
        var csv = new CsvWriter(writer, CultureInfo.InvariantCulture,true);
        csv.WriteRecords(myResult );
        var fileStreamResult = new FileStreamResult(memStream, "text/csv");
        csv.Dispose();
        writer.Dispose();
        return fileStreamResult;
    }
3 Answers

You need to move the stream's current position to the start with :

memStream.Position=0;

FileStreamResul will start reading from the stream's current position.

It sounds like something is being disposed of too early. I'd typically step through to see where the code gets to before the error is thrown.

Try removing the using from the "using var memStream" line(i've found c# 8.0 using statements sometimes don't quite work as expected) or wrapping it in a traditional using block.

When you dispose csv or writer they dispose base stream. Just don't dispose any stream. FileStreamResult will dispose baseStream when it sends it's data.

So remove these two lines of code. csv.Dispose(); writer.Dispose();

Related