I have a directory full of hundreds of text files. I need to loop through each of them, writing (appending) their contents to a single file.
This code is overwriting the target file with each new file the StreamReader opens. How do I append the text to the bottom of the target file instead of overwriting it?
static void Main(string[] args) { var sourceDirectory = @"C:\target\new\"; var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt"); foreach (string currentFile in txtFiles) { StreamReader exportedfiles = new StreamReader(currentFile, System.Text.Encoding.Default); using (FileStream readStream = File.OpenRead(currentFile)) //Specify path for the combined file that will be created. using (FileStream writeStream = File.OpenWrite("C:\\file.txt")) { BinaryReader reader = new BinaryReader(readStream); BinaryWriter writer = new BinaryWriter(writeStream); byte[] buffer = new byte[10240]; //Equals a 10mb buffer. int bytesRead; while ((bytesRead = readStream.Read(buffer, 0, 10240)) > 0) { writeStream.Write(buffer, 0, bytesRead); } } }
You run the following line for each file:
using (FileStream writeStream = File.OpenWrite("C:\\file.txt"))
which means you destroy it and recreate it for each file.
You need to re-organise the two loops (Not certain if I did the moving of lines - there might be a problem with closing braces but you get the idea)
static void Main(string[] args) { var sourceDirectory = @"C:\target\new\"; var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt"); //Specify path for the combined file that will be created. using (FileStream writeStream = File.OpenWrite("C:\\file.txt")) { BinaryWriter writer = new BinaryWriter(writeStream); foreach (string currentFile in txtFiles) { StreamReader exportedfiles = new StreamReader(currentFile, System.Text.Encoding.Default); using (FileStream readStream = File.OpenRead(currentFile)) BinaryReader reader = new BinaryReader(readStream); byte[] buffer = new byte[10240]; //Equals a 10mb buffer. int bytesRead; while ((bytesRead = readStream.Read(buffer, 0, 10240)) > 0) { writeStream.Write(buffer, 0, bytesRead); } } }
You sir are a genius. That's so much easier than what I was trying to do, and it worked great, thank you so much!
Olaf Doschke
You don't even need a string array using ReadAllText()/AppendAllText(), but it's a good idea in terms of RAM usage and read/write flow to use a binary reader going through a smaller buffer. 10240 is 10KB, but already way better than reading byte by byte.
using (FileStream writeStream = File.OpenWrite("C:\\file.t
which means you destroy it and recreate it for each file.
You need to re-organise the two loops (Not certain if I did the moving of lines - there might be a problem with closing braces but you get the idea)
Open in new window