How to read Text from multiple files and write it to a single file using StreamReader and StreamWriter in C#?

Here is an example of using StreamReader and StreamWriter class in C# to Read a number of text files from the source location and writing the contents of all the text files into a single Final Large file.

The sample code below get the list of all text files in the source folder and loops through the list and uses StreadReader to read the content of all the files into a variable of the type StringBuilder and then uses the StreamWriter to write the content to a Final Single text file.
As you can see the code encloses the StreamReader and StreamWriter within a using statement. Doing so helps in closing the StreamReader and StreamWriter implicitly after use. As they are enclosed within the using statement, its not necessary to manually close or dispose them in the finally block of the try catch statement.
using System;
using System.IO;
using System.Text;
 
class Program
{
 
    static void Main(string[] args)
    {
 
        string mydirpath =
          Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
        StringBuilder strFile = new StringBuilder();
 
        foreach (string txtName in txtFileList)
        {
            using (StreamReader sr = new StreamReader(txtName))
            {
                strFile.AppendLine(txtName.ToString());
                strFile.AppendLine("**********");
                strFile.Append(sr.ReadToEnd());
                strFile.AppendLine();
                strFile.AppendLine();
            }
 
        }
 
        using (StreamWriter outfile =
            new StreamWriter(mydirpath + @"\\FinalOutputFile.txt"))
        {
            outfile.Write(strFile.ToString());
        }
    }

}

Happy Programming

Robert