Csvhelper: Write csv file to string?

Created on 2 Apr 2013  路  4Comments  路  Source: JoshClose/CsvHelper

I would like to use the csvhelper to export a list of objects to a csv file in the browser. All I see in the documentation are ways to write directly to a file - can you return the csv file as a string for export?

I tried something like this, but the 'WriteRecords' method is closing the memory stream:

c# using (var memStream = new MemoryStream()) { using (var csv = new CsvWriter(new StreamWriter(memStream))) { csv.WriteRecords(events); return File(memStream, "text/csv", "Report123.csv"); } }

Most helpful comment

Found this via google and the answer is a bit old so thought I'd give it an update for anyone else who finds this.

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture, true))
{
    csv.WriteRecord(csvRow);
    csv.Flush();
    var newRecord = writer.ToString();
}

All 4 comments

Yes. That is what most of the unit tests do...

C# using( var stream = new MemoryStream() ) using( var reader = new StreamReader( stream ) ) using( var writer = new StreamWriter( stream ) ) using( var csv = new CsvWriter( writer ) ) { csv.WriteRecords( events ); writer.Flush(); stream.Position = 0; var text = reader.ReadToEnd(); }

Or something similar. I did this from memory so not sure if it'll compile. ;)

Thanks Josh, that did it. This is a great library!

You're welcome.

Found this via google and the answer is a bit old so thought I'd give it an update for anyone else who finds this.

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture, true))
{
    csv.WriteRecord(csvRow);
    csv.Flush();
    var newRecord = writer.ToString();
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

shinriyo picture shinriyo  路  6Comments

hellboy81 picture hellboy81  路  6Comments

Wagimo picture Wagimo  路  4Comments

mabead picture mabead  路  3Comments

RifS picture RifS  路  5Comments