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");
}
}
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();
}
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.