在C#中将数据写入CSV文件
我试图使用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}\n", 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 only single record in the csv file which is last one. How can I write all the rows in the csv
file.
更新
我天真的天,我建议手动(这是一个简单的问题的一个简单的解决方案),但是由于这变得越来越受欢迎,我建议使用一个库进行所有安全检查等。
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 a library 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}"
编辑