Search code examples
c#asp.net-core.net-5csvhelper

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


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

Solution

  • 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.