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 m
Pass true
as the append parameter of the constructor:
TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
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();
Change your constructor to pass true as the second argument.
TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
Best thing is
File.AppendAllText("c:\\file.txt","Your Text");
using (StreamWriter writer = File.AppendText(LoggingPath))
{
writer.WriteLine("Text");
}
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);
}