Solved

Append text to file

Posted on 2016-07-14
4
37 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
4 Comments
 
LVL 32

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Windows Service to Receive TCP Packets 4 39
c# if statement weird reaction 3 29
install app on other machine 13 11
XML & .net 5 19
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
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.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

705 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now