[c#] How to write data to a text file without overwriting the current data

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.

This question is related to c# text overwrite

The answer is


Look into the File class.

You can create a streamwriter with

StreamWriter sw = File.Create(....) 

You can open an existing file with

File.Open(...)

You can append text easily with

File.AppendAllText(...);

Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();

First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }

You have to open as new StreamWriter(filename, true) so that it appends to the file instead of overwriting.


using (StreamWriter writer = File.AppendText(LoggingPath))
{
    writer.WriteLine("Text");
}

Best thing is

File.AppendAllText("c:\\file.txt","Your Text");

Change your constructor to pass true as the second argument.

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