Jevon Jevon - 11 days ago 8
C# Question

appending header to file that does not exist then append after

With some previous feedback from the community I have implemented a function which checks if a file exists, if it doesn't then it writes the header and the data but if it does exist it only appends to it. Well that's what it's supposed to do but all it does is write the data without the headers. It's as if it jumps out of the first condition and just goes to the next one. Where am I going wrong?

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();
}
}
}

Answer

The problem is that File.WriteAllText overrides the content of the file, so your 2nd File.WriteAllText overrides the headers. You can change your code as follows:

        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();
        }
Comments