?
Solved

Append text to file

Posted on 2016-07-14
4
Medium Priority
?
70 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 2000 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

Technology Partners: 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

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

800 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