读取和写入csv文件并删除逗号

时间:2020-01-24 13:50:22

标签: c#

我正在尝试写到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();
}


1 个答案:

答案 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,并且您可以在循环中继续使用它来写入所有行。

相关问题