How to read Text from multiple files and write it to a single file using StreamReader and StreamWriter in C#?
Posted by admin on Wednesday, 6 November 2013
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.
static void Main(string args)
string mydirpath =
string txtFileList = Directory.GetFiles(mydirpath, "*.txt");
StringBuilder strFile = new StringBuilder();
foreach (string txtName in txtFileList)
using (StreamReader sr = new StreamReader(txtName))
using (StreamWriter outfile =
new StreamWriter(mydirpath + @"\\FinalOutputFile.txt"))