Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write at the next line in the next opening of the csv file?

At first run, my program, writes to a csv file in the first line, But, when I'm running my program at the second.. third.. time, it runs over the first line.. how can i correct it?

I would like to have a CSV file input of all the entering to my program.

The code is as follows:

private void WriteToCsvFile()
{
    var us = users.ElementAt(0);
    string names = "Number',";
    string userAnswer = (us.userName + ",");
    foreach (string ss in user)
    {
        string str = Path.GetFileName(ss);
        names = names + str + ",";
    }
    foreach (string ans in us.answer)
    {
        userAnswer = userAnswer + ans + ",";
    }

    using (StreamWriter sw = new StreamWriter("EntranceLog.csv"))
    {
        sw.WriteLine(names);
        sw.WriteLine(userAnswer);

    }

    this.Close();
}
like image 791
Roy Doron Avatar asked Oct 28 '12 09:10

Roy Doron


1 Answers

Add true parameter in the constructor:

using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))

The second parameter named append controls whether an existing file shall be overwritten or appended. MSDN states:

true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

like image 141
Amiram Korach Avatar answered Sep 20 '22 07:09

Amiram Korach