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



Data > From Textto specify the delimiters you wantNextRecord()afterWriteHeadertoo. That's what CsvWriter itself does