Ani Ani - 3 months ago 15
C# Question

Append data to a .csv File using C#

The following code writes the data and is working fine, but I want to add more than one client (maybe 10) in the .csv file. How can I achieve this. Thanks in advance.

private void createFileButton_Click(object sender, EventArgs e)
{
string newFileName = "C:\\client_20100913.csv";

string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;

//Header of the .csv File
string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

File.WriteAllText(newFileName, clientHeader);
File.AppendAllText(newFileName, clientDetails);

MessageBox.Show("Client Added", "Added", MessageBoxButtons.OK);
}

Answer

If you want to append the client information to an existing file, how about:

string newFileName = "C:\\client_20100913.csv";

string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;


if (!File.Exists(newFileName))
{
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

File.AppendAllText(newFileName, clientDetails);

This way the header line is only written the first time, when the file is created.

Although it would probably be even nicer to provide a list-detail view that lets you view all clients, add and remove clients, select a client to edit details, and save the complete file with all clients.