Jonhy Oliveira
Jonhy Oliveira

Reputation: 23

Line erased when i write a new line to a .txt file - Windows Forms

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.

what happens

whats supposed to happen

Upvotes: 0

Views: 67

Answers (2)

Eser
Eser

Reputation: 12546

Use

File.AppendText(filepath, text);

or

using (var filewrite = new StreamWriter(filepath, append: true))
{
    filewrite.Write(.....);
}

Upvotes: 4

Camden Reslink
Camden Reslink

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

Related Questions