Write to a File using CsvHelper in C#

廉价感情. 提交于 2019-12-18 12:52:17

问题


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.


回答1:


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
}



回答2:


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:


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.




回答4:


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


来源:https://stackoverflow.com/questions/23192696/write-to-a-file-using-csvhelper-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!