Reputation: 23
I'm just a code enthusiast.
This code is from a chronometer I'm doing and I'm using this code on a button press event. The intent is to write on a .txt file the current time on the chronometer and the time the button was pressed.
System.IO.StreamWriter filewrite = new System.IO.StreamWriter(@"C:\Users\joaof\source\repos\WindowsFormsApp2\WindowsFormsApp2\Resources\times.txt");
filewrite.Write("\r\n" + label1.Text + "\r\nAt: " + System.DateTime.Now + "\r\n");
filewrite.Close();
The problem is that whenever i click the button again to save a new time it erases the previous one and writes it.
Upvotes: 0
Views: 67
Reputation: 12546
Use
File.AppendText(filepath, text);
or
using (var filewrite = new StreamWriter(filepath, append: true))
{
filewrite.Write(.....);
}
Upvotes: 4
Reputation: 93
You need to be in append mode, try the following:
System.IO.StreamWriter filewrite = new System.IO.StreamWriter(@"C:\Users\joaof\source\repos\WindowsFormsApp2\WindowsFormsApp2\Resources\times.txt", append: true);
filewrite.Write("\r\n" + label1.Text + "\r\nAt: " + System.DateTime.Now + "\r\n");
filewrite.Close();
Notice the append: true
Upvotes: 1