将标题追加到不存在的文件然后追加

时间:2016-11-21 20:43:14

标签: c# winforms

根据社区的一些先前的反馈,我已经实现了一个检查文件是否存在的函数,如果没有,则它会写入标题和数据但是如果它确实存在则只附加到它。那就是它应该做的,但它只是在没有标题的情况下写入数据。就好像它跳出了第一个条件,然后转到下一个条件。我哪里错了?

private void button6_Click_2(object sender, EventArgs e)
    {

        int count_row = dataGridView1.RowCount;
        int count_cell = dataGridView1.Rows[0].Cells.Count;
        string path = "C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv";
        string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
        + "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM";


        MessageBox.Show("Please wait while " + comboBox5.Text + " table is being exported..");

        for (int row_index = 0; row_index <= count_row - 2; row_index++)
        {

            for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
            {
                textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";

            }
            textBox8.Text = textBox8.Text + "\r\n";

            if (!File.Exists(path))
            {
                System.IO.File.WriteAllText(path, rxHeader);
                System.IO.File.WriteAllText(path, textBox8.Text);
            }
            else
            {    
                System.IO.File.AppendAllText(path, textBox8.Text);
                MessageBox.Show("Export  of " + comboBox5.Text + " table is complete!");
                textBox8.Clear();
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

问题是File.WriteAllText会覆盖文件的内容,因此第二个File.WriteAllText会覆盖标头。您可以按如下方式更改代码:

        if (!File.Exists(path))
        {
            System.IO.File.WriteAllText(path, rxHeader + textBox8.Text);
        }
        else
        {    
            System.IO.File.AppendAllText(path, textBox8.Text);
            MessageBox.Show("Export  of " + comboBox5.Text + " table is complete!");
            textBox8.Clear();
        }