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);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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);

Method 2

Use File.AppendAllLines. That should do it

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

Method 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);
}

Method 4

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.

Method 5

Use

public static void AppendAllLines(
string path,
IEnumerable contents
)

Method 6

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

Method 7

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x