Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to a text file using WriteAllLines

Tags:

c#

asp.net

I am using the following code to write in a text file. My problem is that every time the following code is executed it empties the txt file and creates a new one. Is there a way to append to this txt file?

string[] lines = {DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(), message, type, module };
System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines);
like image 971
user1292656 Avatar asked Mar 13 '13 07:03

user1292656


3 Answers

Use File.AppendAllLines. That should do it

System.IO.File.AppendAllLines(
       HttpContext.Current.Server.MapPath("~/logger.txt"), 
       lines);
like image 130
nunespascal Avatar answered Nov 16 '22 06:11

nunespascal


File.AppendAllLines should help you:

string[] lines = {DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(), message, type, module };
System.IO.File.AppendAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines);
like image 20
Shrivallabh Avatar answered Nov 16 '22 07:11

Shrivallabh


You could use StreamWriter; if the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

string[] lines = { DateTime.Now.Date.ToShortDateString(), DateTime.Now.TimeOfDay.ToString(), message, type, module };

using(StreamWriter streamWriter = new StreamWriter(HttpContext.Current.Server.MapPath("~/logger.txt"), true))
{
    streamWriter.WriteLine(lines);
}
like image 3
jacob aloysious Avatar answered Nov 16 '22 06:11

jacob aloysious