隨着社區的一些以前的反饋,我已經實現了一個函數,用於檢查文件是否存在,如果不存在,那麼它會寫入頭文件和數據,但如果它存在它只能附加到它。那麼這就是它應該做的,但它所做的只是寫入沒有標題的數據。就好像它跳出第一個條件,然後進入下一個條件。我哪裏錯了?將頭添加到不存在的文件然後追加
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