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 Stream开发者_开发知识库Writer(@"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.
Pass true
as the append
parameter of the constructor:
TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
Change your constructor to pass true as the second argument.
TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
You have to open as new StreamWriter(filename, true)
so that it appends to the file instead of overwriting.
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();
Best thing is
File.AppendAllText("c:\\file.txt","Your Text");
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(...);
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);
}
using (StreamWriter writer = File.AppendText(LoggingPath))
{
writer.WriteLine("Text");
}
none of the above did not work I found the solution myself
using (StreamWriter wri = File.AppendText("clients.txt"))
{
wri.WriteLine(eponimia_txt.Text + "," + epaggelma_txt.Text + "," + doy_txt.Text + "," + dieuthini_txt.Text + ","
+ proorismos_txt.Text + "," + poly_txt.Text + "," + sxePara_txt.Text + "," + afm_txt.Text + ","
+ toposFortosis_txt.Text + ",");
}
精彩评论