Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

overwrite

c#

text

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.

like image 579
llk Avatar asked Sep 06 '25 13:09

llk


2 Answers

Pass true as the append parameter of the constructor:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
like image 200
SLaks Avatar answered Sep 09 '25 05:09

SLaks


Change your constructor to pass true as the second argument.

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
like image 44
sarvesh Avatar answered Sep 09 '25 04:09

sarvesh