How to add a new line to a txt file

I want to add a new line with text to the date.txt file, but instead of adding it to the existing date.txt file, the application creates a new date.txt file.

TextWriter tw = new StreamWriter("date.txt"); // write a line of text to the file tw.WriteLine(DateTime.Now); // close the stream tw.Close(); 

I want to open a txt file, add text, close it, and then click something: open the date.txt file, add the text and close it again.

So, I can get:

Button pressed: txt is open → the current time is added, then close it. Another button is pressed, txt is open → the text “OK” or “NOT OK” is added on the same line, then close it again.

So my txt file will look like this:

 2011-11-24 10:00:00 OK 2011-11-25 11:00:00 NOT OK 

How can i do this? Thank!

+85
c # stream winforms text-files
Nov 24 '11 at 10:26
source share
4 answers

You can do it easily using

 File.AppendAllText("date.txt", DateTime.Now.ToString()); 

If you need a new line

 File.AppendAllText("date.txt", DateTime.Now.ToString() + Environment.NewLine); 

In any case, if you need your code, follow these steps:

 TextWriter tw = new StreamWriter("date.txt", true); 

with a second parameter indicating add file.
Check here StreamWriter Syntax.

+181
Nov 24 '11 at 10:27
source share

No new line:

 File.AppendAllText("file.txt", DateTime.Now.ToString()); 

and then to get a new line after OK:

 File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine)); 
+18
Nov 24 '11 at 10:30
source share

Why not do it with a single method call:

 File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() }); 

which will make a new line for you and allow you to insert multiple lines at once.

+2
Dec 20 '16 at 23:50
source share
 var Line = textBox1.Text + "," + textBox2.Text; File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine); 
0
May 28 '17 at 7:18
source share



All Articles