This post will discuss how to append text to an existing file in C#.

1. Using File.AppendAllText() method

The most common solution to append text to an existing file is using the AppendAllText() method from the File class. It appends the given text to the end of the file and then closes the file. Here’s an example of its usage:

Download Code

 
The File.AppendAllText() method creates a new file if the specified file doesn’t exist. However, it throws DirectoryNotFoundException if the specified directory doesn’t exist, and UnauthorizedAccessException if the path specified a directory. Note that the file handle is guaranteed to be closed, even if an exception is raised.

 
You may also use the File.AppendAllLines() method to append lines to a file. It is often required to append all text from a file to the target file. This can be achieved as follows:

Download Code

2. Using File.AppendText() method

The StreamWriter class provides several utility methods for writing to a file. You can use either its Write() or WriteLine() method for adding a text to the stream. You can get a StreamWriter instance using the File.AppendText() method, which appends UTF-8 text to an existing file.

The following example uses the StreamWriter.Write() method to append a string to a file. Note that it creates a new file if the specified file does not exist. If you need to append the text followed by a line terminator, consider using the StreamWriter.WriteLine() method instead.

Download Code

 
The File.AppendText() method is equivalent to calling StreamWriter(String, true), where true parameter indicates append mode. The following example demonstrates calling this constructor overload.

Download Code

That’s all about appending a text to an existing file in C#.