Append a File in C#

The File class provides three methods to append an existing file.

  • AppendText

  • AppendAllText

  • AppendAllLines
The AppendText method creates a StreamWriter object that appends UTF-8 encoded text to an existing text file.

string fileName = @"C:\Temp\Mahesh.txt";
using
(StreamWriter sw = File.AppendText(fileName))
{
    sw.WriteLine("--------- Append Text Start ----------");
    sw.WriteLine("New author started");
    sw.WriteLine("a book on Files Programming ");
    sw.WriteLine("using C#");
    sw.WriteLine("--------- Append Text End ----------");
}

The AppendAllText method opens a file, appends a specified string to the file and then closes the file. If the file does not exist, this method creates a new file, writes the specified string to the file, and then closes the file.

string fileName = @"C:\Temp\Mahesh.txt";
string
appendText = "Append all text method ----";
File
.AppendAllText(fileName, appendText);
File
.AppendAllText(fileName, "Append some more text");
File
.AppendAllText(fileName, "Append all text end");

// Read all text

string
readText = File.ReadAllText(fileName);
Console
.WriteLine(readText);

The AppendAllLines method appends lines to a file and then closes the file.


// We can read a line from one file and write to other file

string
fileName = @"C:\Temp\Mahesh.txt";          
string
[] lines = File.ReadAllLines(fileName);         
// Write all lines to a new file

string
outputFileName = @"C:\temp\WriteLinesFile.txt";
File
.WriteAllLines(outputFileName, lines);

// Append more lines

string
[] moreLines = new string[]{"Line 1 goes here", "Line 2 goes here" };
File
.AppendAllLines(outputFileName, moreLines);

// Read all text

string
readText = File.ReadAllText(outputFileName);
Console
.WriteLine(readText);

Up Next
    Ebook Download
    View all
    Learn
    View all