Append to Text File in C#

  1. Append to a Text File With the File.AppendAllText() Method in C
  2. Append to a Text File With the StreamWriter Class in C

This tutorial will discuss the methods to append to a text file in C#.

Append to a Text File With the File.AppendAllText() Method in C

The File.AppendAllText() method in C# is used to open an existing file, append all the text to the end of the file and then close the file. If the file does not exist, the File.AppendAllText() method creates a new empty file and writes the data in it. The File.AppendAllText() method takes the file path and the text to be written as its arguments. The following code example shows us how to append data to a text file with the File.AppendAllText() method in C#.

using System;
using System.IO;

namespace append_to_file
{
    class Program
    {
        static void Main(string[] args)
        {
            File.AppendAllText(@"C:\File\file.txt", "This is the new text" + Environment.NewLine);
        }
    }
}

file.txt before running code:

this is all the text in this file

file.txt after running code:

this is all the text in this file
This is the new text

In the above code, we appended the text This is the new text and a new line at the end of the file.txt file inside the path C:\File with the File.AppendAllText() method in C#.

Append to a Text File With the StreamWriter Class in C

We can achieve the same goal with the StreamWriter class. The StreamWriter class is used to write text to a stream or a file in C#. The SreamWriter.WriteLine() method writes a whole line in C#. We can initialize an object of the StreamWriter class with the File.AppendText() method to initialize an instance of StreamWriter class that would append the data to the file. The following code example shows us how we can append data to the end of a text file with the StreamWriter class in C#.

using System;
using System.IO;

namespace append_to_file
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter sw = File.AppendText(@"C:\File\file.txt"))
            {
                sw.WriteLine("This is the new text");
            }
        }
    }
}

file.txt before running code:

this is all the text in this file

file.txt after running code:

this is all the text in this file
This is the new text

In the above code, we appended the text This is the new text and a new line at the end of the file.txt file inside the path C:\File with the sw.WriteLine() method in C#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp File

  • Delete All Files in a Directory in C#
  • Read a File to String in C#