Reputation: 481
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.
Upvotes: 2
Views: 5954
Reputation: 8194
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");
Upvotes: 0
Reputation: 4808
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
.
Upvotes: 1