'Wrong output when Write a list of class using CsvHelper in C#
I would like to export my class in .csv file, i follow this comment : https://stackoverflow.com/a/38088636/10152334
but when i export (in Buses_Data.Buses_List), i have wrong data output, all data are on same line :
public void ExportToCSV(Buses_Data classToExport, string filepath)
{
try
{
if (File.Exists(filepath))
{
Console.WriteLine("Le fichier existe");
System.IO.File.Delete(filepath);
Console.WriteLine("l'ancien fichier à été supprimé");
}
Console.WriteLine("Export :...");
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
}
}
Console.WriteLine("Export CSV: OK");
}
catch (Exception i)
{
Console.WriteLine("Error ! " + i);
}
}
I don't know why the code doesn't work
Right output (Data not corresponding)

Edit 2 : I tried this comment : Enforce LF line endings with CsvHelper
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
sw.NewLine = "\n";
cw.NextRecord();
}
}
I have better result but i Bus N°1 is on first line, not in second line
Solution :
using (StreamWriter sw = new StreamWriter(filepath))
using (CsvWriter cw = new CsvWriter(sw))
{
cw.WriteHeader<Bus>();
cw.NextRecord();
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
//sw.NewLine = "\n";
cw.NextRecord();
}
}
Solution 1:[1]
Based on answer of GitHub issue, written by Josh Close:
You need to call
NextRecord()when you're done writing the header. This is so you can write more fields manually before or after.
I tried it, it works well.
Solution 2:[2]
Have you tried CsvWriter.NextRecord?
foreach (Bus emp in classToExport.Buses_List)
{
cw.WriteRecord<Bus>(emp);
cw.NextRecord();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | koviroli |
| Solution 2 | Parrish Husband |



