Reputation: 2560
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);
Upvotes: 11
Views: 28804
Reputation: 6762
In all the above cases I prefer to use using to make sure that open and close file options will be taken care of.
Upvotes: 0
Reputation: 2903
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);
Upvotes: 22
Reputation: 2597
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);
}
Upvotes: 3
Reputation: 36
Use
public static void AppendAllLines( string path, IEnumerable contents )
Upvotes: 1
Reputation: 412
three function are available ..File.AppendAllLine ,FileAppendAllText and FileAppendtext..you can try as u like...
Upvotes: 0
Reputation: 2803
Do something like this :
string[] lines = {DateTime.Now.Date.ToShortDateString(),DateTime.Now.TimeOfDay.ToString(), message, type, module };
if (!File.Exists(HttpContext.Current.Server.MapPath("~/logger.txt")))
{
System.IO.File.WriteAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines);
}
else
{
System.IO.File.AppendAllLines(HttpContext.Current.Server.MapPath("~/logger.txt"), lines);
}
So if file is not exists it will create and write in file and if file exists it will append on file.
Upvotes: 2
Reputation: 17724
Use File.AppendAllLines
. That should do it
System.IO.File.AppendAllLines(
HttpContext.Current.Server.MapPath("~/logger.txt"),
lines);
Upvotes: 9