Write to a File using CsvHelper in C#

Nayana Priyankara picture Nayana Priyankara · Apr 21, 2014 · Viewed 55.4k times · Source

I tried to write to CSV file using CsvHelper in C#.
This is the link to the library http://joshclose.github.io/CsvHelper/

I used the code in web site.

Here is my code:

var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
    csv.WriteRecord(value);
}

It writes only a part of data to csv file.
Last rows were missing.
Could you please help with this.

Answer

Greg R Taylor picture Greg R Taylor · Oct 15, 2016

You need to flush the stream. The Using statement will flush when out of scope.

using (TextWriter writer = new StreamWriter(@"C:\test.csv", false, System.Text.Encoding.UTF8))
{
    var csv = new CsvWriter(writer);
    csv.WriteRecords(values); // where values implements IEnumerable
}