0

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!

3
  • File.WriteAllText overwrites your file each time, use AppendAllText instead. Write the header in first case if !Exists Commented Sep 14, 2016 at 4:22
  • @CRice writealltext is only called if the file does not exist Commented Sep 14, 2016 at 4:45
  • Seems I missed that due to bad formatting that is now fixed Commented Sep 14, 2016 at 5:29

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks The shooter, simplest solution! :)
1

Just change your code to the following:

string newFileName = "C:\\names.csv";
string nameDetails = txtName.Text + "," + txtLastName.Text + "," + txtAge.Text;
if (!File.Exists(newFileName))
{
    string nameHeader = "Name,LastName,Age\n"; //No point concatenating
    nameDetails = nameHeader + nameDetails;
}
File.AppendAllText(newFileName, nameDetails);

Side Note: You can keep things a bit more tidy by using string.Format. If you do, your code will become something like this:

string newFileName = "C:\\names.csv";
string nameDetails = string.Format("{0},{1},{2}\n", txtName.Text, txtLastName.Text, txtAge.Text);
if (!File.Exists(newFileName))
{
    nameDetails = "Name,LastName,Age\n" + nameDetails;
}
File.AppendAllText(newFileName, nameDetails);

And if you're using the latest c# 6, things can be made even nicer:

string newFileName = "C:\\names.csv";
string nameDetails = $"{txtName.Text},{txtLastName.Text},{txtAge.Text}\n");
if (!File.Exists(newFileName))
{
    nameDetails = "Name,LastName,Age\n" + nameDetails;
}
File.AppendAllText(newFileName, nameDetails);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.