How to Append a file in C#

By FoxLearn 6/25/2024 3:44:22 AM   53
Appending data to a file in C# can be done using various methods provided by the .NET framework.

Below are three common ways to append text to a file in C#:

Using StreamWriter with append parameter

string fileName = "c://demo.txt";
string line1 = "Welcome to FoxLearn.";
string line2 = "This is the text to append.";
using (StreamWriter sw = new StreamWriter(fileName, true))
{
      sw.WriteLine(line1);
      sw.WriteLine(line2);
}

Using File.AppendAllText

string fileName = "c://demo.txt";
string textToAppend = "Welcome to FoxLearn.";
//c# write to file append
File.AppendAllText(fileName, textToAppend + Environment.NewLine);

Using File.AppendText

string fileName = "c://demo.txt";
string line1 = "Welcome to FoxLearn.";
string line2 = "This is the text to append.";
using (StreamWriter sw = File.AppendText(fileName))
{
      sw.WriteLine(line1);
      sw.WriteLine(line2);
}

You can also use FileInfo class to help you append text to a file

string fileName = @"C:/fileName.txt";
FileInfo fi = new FileInfo(fileName);
using (StreamWriter sw = fi.AppendText())
{
   sw.WriteLine("C# Programming");
   sw.WriteLine("Welcome to FoxLearn");
}
// Read all text
string readText = File.ReadAllText(fileName);

StreamWriter: Creates a StreamWriter object to write text to the file. The second parameter in the constructor (true) specifies that the text should be appended to the file if it exists.

File.AppendAllText: A static method from the File class that appends the specified text to the file.

File.AppendText: Returns a StreamWriter object to append text to the file.

You can choose the method that best fits your needs based on your familiarity with the classes and your specific use case.