MrPatterns
MrPatterns

Reputation: 4434

How do I merge several text files into one text file using C#?

I want to merge all of the tab-delimited text files in a directory into one giant text file. The files don't have headers and the columns in all of the files are all aligned properly with each other so let's assume we don't have to worry about formatting consistency issues.

I just have to stitch/join/merge all of the files together in no particular order.

Here's my code that works:

    string[] array = Directory.GetFiles(@"C:\MergeThis", "*.txt");

    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    for (int nCount = 0; nCount <= array.Count(); nCount++)
    {
        sb.Append(System.IO.File.ReadAllText(array[nCount])); 
    }

    string output = sb.ToString();    

    string outputFilePath = @"C:\MERGED DATA.txt";
    System.IO.File.WriteAllText(outputFilePath, output);

My question is..is there a better/faster/more concise way of doing this?

Upvotes: 3

Views: 9410

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

Dont know if thats faster than yours but here is a solution provided by n8wrl in their answer here:

using (var output = File.Create("output"))
{
    foreach (var file in new[] { "file1", "file2" })
    {
        using (var input = File.OpenRead(file))
        {
            input.CopyTo(output);
        }
    }
}

Note:- Stream.CopyTo Method is a feature of .Net 4.0

Upvotes: 6

Related Questions