TheDeveloperBlog.com


C# File.AppendAllText Method

File.AppendAllText appends a string to a file. It creates a text file if one does not already exist. It avoids inefficient code that would have to read in the entire file. It is ideal for log files and journal data.


Example. First, this File.AppendAllText example first creates a text file and writes a string to it. Then it appends text on every following call. If the file already exists when the program starts, the file will be appended to.

Based on:

.NET 4.5

C# program that uses File.AppendAllText

using System.IO;

class Program
{
    static void Main()
    {
	//
	// 1. Use AppendAllText to write one line to the text file.
	//
	File.AppendAllText("C:\\perls.txt", "first part\n"); // <-- use \\ not \ in path
	//
	// 2. The file now has a newline at the end, so write another line.
	//
	File.AppendAllText("C:\\perls.txt", "second part\n");
	//
	// 3. Write a third line.
	//
	string third = "third part\n"; // <-- string reference
	File.AppendAllText("C:\\perls.txt", third);
    }
}

This example uses File.AppendAllText to open the text file at "C:\perls.txt" for writing. When you run the program for the first time, the file is created if it does not yet exist.

Then: The AppendAllText method is called two more times in the example. Each string appended to the file has a newline at the end.

Tip: This means you will be appending lines to the file, not just words. This is an important detail.


Effect. The example above has a cumulative effect on the file at "C:\perls.txt". When you open the file in that location with Notepad, you see it is added to each time your run the program. This is ideal for simple logging.

Run the program 1 time:

first part
second part
third part

Run the program again:

first part
second part
third part
first part
second part
third part


Internals. I inspected this method in IL Disassembler and found that AppendAllText internally calls StreamWriter, with the second parameter "append" set to true. If you need to process many lines in one append, consider StreamWriter.

StreamWriter

Summary. We appended text to a file using the simplest logic. With File.AppendAllText, try not to call it in a loop, as this will create a StreamWriter and dispose it each time, reducing performance. In that case, use StreamWriter instead.