Search code examples
c#filestream

Appendtext not working


So I'm trying to make a program that calculates and saves your BMI into a file. I tried using appendtext like this.

StreamWriter logboekBMI = new StreamWriter(path + "Logbmi.txt");
logboekBSA.Close();

logboekBMI = File.AppendText(path + "Logbmi.txt");
logboekBMI.WriteLine("BMI: " + bmi.getBMI());
logboekBMI.Close();

And I read the file to a text box like this:

StreamReader logbmi = new StreamReader(path + "Logbmi.txt");
txtLogboek.Text = logbmi.ReadToEnd();

It deletes the line that was already in the file and inserts the new one. It never appends.


Solution

  • If I understand the question correctly, you want to write text to a file without overwriting any text that is already there.

    In that case, you need to define your StreamWriter like so:

    StreamWriter logboekBMI = new StreamWriter(path + "Logbmi.txt", true);
    

    The true parameter means that you want to append text to the file. Without it, you are overwriting the file every time you create a new StreamWriter.