David Tod David Tod - 2 months ago 9
C# Question

Issues append data to a .csv File using C#

I am manipulating a csv file using C# but I have an issue. When I added a new row, the first iteration does successful, but the second one overwrite the same row previous.

Example CSV File:

Name, LastName, Age

David, Todd, 28

Juan, Perez, 30




First iteration:

Name, LastName, Age

David, Todd, 28

Juan, Perez, 30

Pepe, Hernandez, 32




Second iteration:

Name, LastName, Age

David, Todd, 28

Juan, Perez, 30

Pepe, Hernandez, 32Maria,Lopez,35




What am I doing wrong?

This is my code:

string newFileName = "C:\\names.csv";
string nameDetails = txtName.Text + "," + txtLastName.Text + "," + txtAge.Text;
if (!File.Exists(newFileName))
{

string nameHeader = "Name" + "," +
"LastName" + "," + "Age" + Environment.NewLine;

File.WriteAllText(newFileName, nameHeader);

}

File.AppendAllText(newFileName, nameDetails);


Thanks!

Answer

You are missing

+ Environment.NewLine 

while calling

File.AppendAllText

It should be there as well i.e. it should be

File.AppendAllText(newFileName, nameDetails + Environment.NewLine);