用C#将数据写入CSV文件 [英] Writing data into CSV file in C#
问题描述
我正在尝试使用 C# 语言逐行写入 csv
文件.这是我的功能
I am trying to write into a csv
file row by row using C# language. Here is my function
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}
", first, second);
File.WriteAllText(filePath, csv);
整个函数在一个循环中运行,每一行都应该写入csv
文件.就我而言,下一行覆盖了现有行,最后,我在 csv 文件中获得了唯一一条记录,这是最后一条记录.如何写入 csv
文件中的所有行?
The whole function runs inside a loop, and every row should be written to the csv
file. In my case, next row overwrites the existing row and in the end, I am getting an only single record in the csv file which is the last one. How can I write all the rows in the csv
file?
推荐答案
UPDATE
在我幼稚的日子里,我建议手动执行此操作(这是一个简单问题的简单解决方案),但是由于这变得越来越流行,我建议使用库 CsvHelper 执行所有安全检查等.
Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.
CSV 比问题/答案所暗示的要复杂得多.
CSV is way more complicated than what the question/answer suggests.
原答案
因为你已经有了一个循环,考虑这样做:
As you already have a loop, consider doing it like this:
//before your loop
var csv = new StringBuilder();
//in your loop
var first = reader[0].ToString();
var second = image.ToString();
//Suggestion made by KyleMit
var newLine = string.Format("{0},{1}", first, second);
csv.AppendLine(newLine);
//after your loop
File.WriteAllText(filePath, csv.ToString());
或者类似的东西.我的理由是:您不需要为每个项目都写入文件,您只需打开流一次然后再写入.
Or something to this effect. My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.
可以替换
File.WriteAllText(filePath, csv.ToString());
与
File.AppendAllText(filePath, csv.ToString());
如果您想将以前版本的 csv 保留在同一文件中
if you want to keep previous versions of csv in the same file
C# 6
如果您使用的是 c# 6.0,那么您可以执行以下操作
If you are using c# 6.0 then you can do the following
var newLine = $"{first},{second}"
编辑
这是一个链接到一个解释什么的问题Environment.NewLine
确实如此.
Here is a link to a question that explains what Environment.NewLine
does.
这篇关于用C#将数据写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!