user1292656
user1292656

Reputation: 2560

Append to a text file using WriteAllLines

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

Answers (7)

Kurkula
Kurkula

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

Shrivallabh
Shrivallabh

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

jacob aloysious
jacob aloysious

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

Roman.Potapkin
Roman.Potapkin

Reputation: 36

Use

public static void AppendAllLines( string path, IEnumerable contents )

Upvotes: 1

j.s.banger
j.s.banger

Reputation: 412

three function are available ..File.AppendAllLine ,FileAppendAllText and FileAppendtext..you can try as u like...

Upvotes: 0

CodeGuru
CodeGuru

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

nunespascal
nunespascal

Reputation: 17724

Use File.AppendAllLines. That should do it

System.IO.File.AppendAllLines(
       HttpContext.Current.Server.MapPath("~/logger.txt"), 
       lines);

Upvotes: 9

Related Questions