我正在尝试写到csv,但是我只将最后一行写到csv, 我认为它正在覆盖前一行,因为它在循环语句中,但是我不知道如何使它起作用? 生成的csv已成功删除该行中的所有逗号 感谢您的协助,因为我是新手, 谢谢
private void button1_Click(object sender, EventArgs e) {
TextFieldParser tfp = new TextFieldParser("C:\\imports\\test1.csv");
tfp.Delimiters = new string[] { "," };
tfp.HasFieldsEnclosedInQuotes = true;
while (!tfp.EndOfData) {
string[] fields = tfp.ReadFields();
// remove the commas and double-quotes from the fields.
for (int i = 0; i < fields.Length; i++)
fields[i] = fields[i].Replace(",", " ").Replace("\"", "");
// this is the output
using (var writer = new System.IO.StreamWriter("c:\\imports\\testing.csv"))
writer.WriteLine(string.Join(",", fields) + "\n");
}
MessageBox.Show("Complete");
tfp.Close();
}
答案 0 :(得分:1)
您的假设是正确的,每次您写新行时,它都会覆盖文件。这是由于每次都打开一个新的StreamWriter
引起的,相反,您应该打开一次StreamWriter
并继续使用相同的实例,例如:
private void button1_Click(object sender, EventArgs e) {
TextFieldParser tfp = new TextFieldParser("C:\\imports\\test1.csv");
tfp.Delimiters = new string[] { "," };
tfp.HasFieldsEnclosedInQuotes = true;
using (var writer = new System.IO.StreamWriter("c:\\imports\\testing.csv")) {
while (!tfp.EndOfData) {
string[] fields = tfp.ReadFields();
// remove the commas and double-quotes from the fields.
for (int i = 0; i < fields.Length; i++)
fields[i] = fields[i].Replace(",", " ").Replace("\"", "");
// this is the output
writer.WriteLine(string.Join(",", fields) + "\n");
}
}
MessageBox.Show("Complete");
tfp.Close();
}
如您所见,我仅在using
循环之前将StreamWriter
语句与while
一起移动了(并添加了大括号以清楚地表明using
的范围声明)。这样,仅创建一个StreamWriter
,并且您可以在循环中继续使用它来写入所有行。