To merge multiple text files into a single file in C#, you can use
System.IO to read each file and append its content to the target file. Here's how:
Basic Example: Merge All .txt Files in a Folder
using System.IO;
string sourceDirectory = @"C:\TextFiles";
string outputFile = @"C:\Merged\combined.txt";
// Get all .txt files in the folder
var files = Directory.GetFiles(sourceDirectory, "*.txt");
// Merge into one file
using (var output = File.CreateText(outputFile))
{
foreach (var file in files)
{
string content = File.ReadAllText(file);
output.WriteLine(content); // Write file content
output.WriteLine(); // Optional: blank line between files
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To merge multiple text files into a single file in C#, you can use
System.IOto read each file and append its content to the target file. Here's how:Basic Example: Merge All
.txtFiles in a FolderVariation: Append Instead of Overwriting
If you want to append to an existing file:
Optional Enhancements
Add File Headers
Sort Files by Name or Date
Summary
File.ReadAllText(path)File.CreateText(path)File.AppendAllText(path, ...)StreamReader/Writer