C# File.AppendAllText

File image with lines of text

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 similar, journaled data.

Example

First, we see an example of the File.AppendAllText method that first creates a text file and writes a string to it, and then appends text to it on every following call. If the file already exists when the program starts, the file will be appended to.

This C# program shows the File.AppendAllText method from System.IO.

Program that uses File.AppendAllText [C#]

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

Overview. 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.

Subsequent calls to File.AppendAllText. The AppendAllText method is called two more times in the example. Each string appended to the file has a newline at the end. This means you will be appending lines to the file, not just words.

Output

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 can see that 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

.NET Framework information

I inspected this method in IL Disassembler and found that AppendAllText internally calls StreamWriter, with the second parameter 'append' set to true. For this reason, if you have logic that needs to process many lines in one append, you can use StreamWriter instead.

Using StreamWriter

Summary

The C# programming language

Here we saw how you can append text to a file using the simplest logic and the smallest amount of C# code. 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.

File Handling
.NET