3

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;
    }
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
HrkBrkkl
  • 613
  • 5
  • 22
  • https://joshclose.github.io/CsvHelper/examples/prerequisites/streams/ – gunr2171 Jun 22 '21 at 15:37
  • `csv.Dispose();` you're here disposing it, so remove this line before returning it. Also, remember that streams implement ' IDisposable', so remember to enclose them in `using` blocks. – Alejandro Jun 22 '21 at 15:37
  • Does this answer your question? [Using CSVHelper to output stream to browser](https://stackoverflow.com/questions/21093150/using-csvhelper-to-output-stream-to-browser) – gunr2171 Jun 22 '21 at 15:37
  • You need to write ROW of data with a Return at end of each row (WriteLine). Then before adding new row Read a line from file to make room for a new row. It is better to do with a List> than a stream. – jdweng Jun 22 '21 at 15:46
  • @gunr2171 it is working but i would like to reuse the same stream and not vonvert to bytearray and then open a new memorystream – HrkBrkkl Jun 22 '21 at 15:53

3 Answers3

3

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.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
1

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.

newky2k
  • 419
  • 5
  • 12
-1

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

MrMoeinM
  • 2,080
  • 1
  • 11
  • 16