Solved

Append text to file

Posted on 2016-07-14
4
39 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 33

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Image(7) 1 53
Sum Column in GridView 3 44
Class object 2 27
Windows Media Player 2 16
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
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, f…

920 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

15 Experts available now in Live!

Get 1:1 Help Now