随着社区的一些以前的反馈,我已经实现了一个函数,用于检查文件是否存在,如果不存在,那么它会写入头文件和数据,但如果它存在它只能附加到它。那么这就是它应该做的,但它所做的只是写入没有标题的数据。就好像它跳出第一个条件,然后进入下一个条件。我哪里错了?将头添加到不存在的文件然后追加
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();
}
}
}
很确定您希望第二次调用是'Append',而不是'Write'。更改为:'System.IO.File.WriteAllText(path,rxHeader);''System.IO.File.AppendAllText(path,textBox8.Text);'。没有这个改变,第二次调用基本上删除文件,然后只写入'textBox8.Text'。 – Quantic
@Quantic这在一定程度上工作,但问题是,标题和第一个记录添加好,但当我关闭该程序并追加一个新的记录。它复制现有记录,然后添加我添加的新记录。 (我的数据存储在我的数据库中,我将其保存并通过我的c#应用程序展示给CSV文件)我不确定这是否很重要 – Jevon