I\'m using the CsvHelper library in an ASP.NET MVC project to export data to CSV, and am finding that the exported data is either cut off, or in the case of smaller lists, n
The reason is because you're not flushing the data in the writer to the stream. The writer will periodically flush itself when it's full, but you need to make sure to do it at the end.
Option 1:
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter))
{
csvWriter.WriteRecords(data);
streamWriter.Flush();
memoryStream.Position = 0;
return File(memoryStream, "text/csv", filename);
}
Option 2:
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter))
{
csvWriter.WriteRecords(data);
} // The stream gets flushed here.
memoryStream.Position = 0;
return File(memoryStream, "text/csv", filename);
}