Solved

Append text to file

Posted on 2016-07-14
4
57 Views
Last Modified: 2016-07-18
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);
                    }
                }
            }

Open in new window

0
Comment
Question by:fcsIT
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 34

Accepted Solution

by:
it_saige earned 500 total points
ID: 41711251
I would use File.ReadAllLines, File.WriteAllLines and File.AppendAllLines

Simple example based on your code -
using System.IO;

namespace EE_Q28957553
{
	class Program
	{
		static void Main(string[] args)
		{
			foreach (string path in Directory.EnumerateFiles(@"C:\target\new\", "*.txt"))
			{
				string[] lines = File.ReadAllLines(path);
				if (!File.Exists("C:\\file.txt"))
					File.WriteAllLines("C:\\file.txt", lines);
				else
					File.AppendAllLines("C:\\file.txt", lines);
			}
		}
	}
}

Open in new window

-saige-
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41711253
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);
                    }
                }
            }

Open in new window

1
 

Author Comment

by:fcsIT
ID: 41711257
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!
0
 
LVL 29

Expert Comment

by:Olaf Doschke
ID: 41711279
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.

Bye, Olaf.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
IEnumerable<T> to a List<T> 8 65
C# Service FileSystemwatcher isse 9 61
Visual Studio 2015 auto inserted code 12 88
ASP.NET data base connection 35 90
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question