How to write data to a text file without overwriting the current data

llk picture llk · Apr 1, 2011 · Viewed 113.8k times · Source

I can't seem to figure out how to write data to a file without overwriting it. I know I can use File.appendtext but I am not sure how to plug that into my syntax. Here is my code:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt");

//Writing text to the file.
tsw.WriteLine("Hello");

//Close the file.
tsw.Close();

I want it to write Hello every time I run the program, not overwrite the previous text file. Thanks for reading this.

Answer

SLaks picture SLaks · Apr 1, 2011

Pass true as the append parameter of the constructor:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);