27

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.

2
  • 1
    Can you show some more of your code? Especially the declaration of writer is interesting. Commented Apr 21, 2014 at 7:21
  • when, I added this code after the loop code is working well writer.Close(); Commented Apr 21, 2014 at 7:32

5 Answers 5

44

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
}
Sign up to request clarification or add additional context in comments.

Comments

10

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

3 Comments

You should Dispose your writer, "using" is a good pratice using (var writer = new StreamWriter(filepath)) { ... }
Starting from CSVHelper 13.0.0 There are breaking change in Factory.CreateWriter joshclose.github.io/CsvHelper/change-log
And for ANSI - Windows-1252?
8

Assuming that writer is some kind of TextWriter, you should add a call to flush the contents before closing the writer:

writer.Flush()

If the last lines are missing, this is the most likely reason.

1 Comment

when, I added this code after the loop code is working well writer.Close();
2

Adding to @greg's answer:

using (var sr = new StreamWriter(@"C:\out.csv", false, Encoding.UTF8)) {
  using (var csv = new CsvWriter(sr)) {
    csv.WriteRecords(values);
  }
}

Comments

0
var configuration = new CsvConfiguration(CultureInfo.InvariantCulture)
          {
              Delimiter = Delimiter
          };
using (var csvWriter = new CsvWriter(writer, configuration))
{
    csvWriter.WriteRecords(itemsData);
    csvWriter.Flush();
}

//This is an example that might help you 

1 Comment

It would be great if you can add an explanation of your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.