Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append data to a .csv File using C#

Tags:

c#

csv

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); 
}
like image 495
Ani Avatar asked Dec 05 '22 01:12

Ani


1 Answers

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.

like image 128
Jeremy Avatar answered Dec 19 '22 11:12

Jeremy