11

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);
TBD
  • 509
  • 7
  • 15
user1292656
  • 2,502
  • 20
  • 48
  • 68

7 Answers7

21

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);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Shrivallabh
  • 2,863
  • 2
  • 27
  • 47
  • AppendAllText does not accept a String Array as the second parameter. The correct answer should be one of those below using the AppendAllLines method. – pierce.jason Mar 27 '15 at 22:44
  • Just a note, this will not clear existing items in text file. – Kurkula Feb 10 '17 at 20:11
9

Use File.AppendAllLines. That should do it

System.IO.File.AppendAllLines(
       HttpContext.Current.Server.MapPath("~/logger.txt"), 
       lines);
nunespascal
  • 17,584
  • 2
  • 43
  • 46
3

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);
}
jacob aloysious
  • 2,547
  • 15
  • 16
2

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.

CodeGuru
  • 2,722
  • 6
  • 36
  • 52
1

Use

public static void AppendAllLines( string path, IEnumerable contents )

0

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

j.s.banger
  • 412
  • 1
  • 6
  • 15
0

In all the above cases I prefer to use using to make sure that open and close file options will be taken care of.

Kurkula
  • 6,386
  • 27
  • 127
  • 202