2

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.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Pedro Lopes
  • 479
  • 2
  • 9
  • 20
  • This code doesn't work at all, where have you copied it from? All you need is the one line `File.AppendAllText("C:\path\to\file\Logbmi.txt", "The text to add");` – Equalsk Feb 12 '16 at 17:00
  • Forgot to say then you just need `File.ReadAllText("C:\path\to\file\Logbmi.txt");` to get it back again – Equalsk Feb 12 '16 at 17:06
  • Possible duplicate of [Append lines to a file using a StreamWriter](http://stackoverflow.com/questions/7306214/append-lines-to-a-file-using-a-streamwriter) – user1666620 Feb 12 '16 at 17:11

2 Answers2

1

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.

user1666620
  • 4,800
  • 18
  • 27
0

Your code seems over complicated for what you want to do. You only need two lines of code, one to save the text and one to read it.

Save text: File.AppendAllText

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

File.AppendAllText("C:\path\to\file\Logbmi.txt", "The BMI to add");

 
Read text: File.ReadAllText

Opens a text file, reads all lines of the file into a string, and then closes the file.

txtLogboek.Text = File.ReadAllText("C:\path\to\file\Logbmi.txt");
Equalsk
  • 7,954
  • 2
  • 41
  • 67