Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a File using CsvHelper in C#

Tags:

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.

like image 202
Nayana Priyankara Avatar asked Apr 21 '14 07:04

Nayana Priyankara


People also ask

Is CSVHelper free?

Many contributors have helped make CsvHelper the great library it is today. Completely free for commercial use.

How do I create a CSV file in C sharp?

First you'll need to create a new Visual Studio C# console application, there are steps to follow to do this. The example code will create a csv file called MyTest. csv in the location you specify. The contents of the file should be 3 named columns with text in the first 3 rows.

How do I save Comma Separated Values in CSV?

To save an Excel file as a comma-delimited file: From the menu bar, File → Save As. Next to “Format:”, click the drop-down menu and select “Comma Separated Values (CSV)” Click “Save”


2 Answers

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 } 
like image 53
Greg R Taylor Avatar answered Oct 21 '22 16:10

Greg R Taylor


when, I added this code after the loop code is working well

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

The problem occurred because I did not close the Connection

like image 31
Nayana Priyankara Avatar answered Oct 21 '22 16:10

Nayana Priyankara