MERGE MANY TEXT FILES INTO SINGLE TEXT FILE USING C#?

Lady Bird Johnson

Total Post:20

Points:140
Posted by  Lady Bird Johnson
C# 
C#
 7849  View(s)
Ratings:
Rate this:
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[] stringArray = Directory.GetFiles(@"C:\MergeFileName", "*.txt");
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     for (int i = 0; i <= stringArray.Count(); i++)
    {
        stringBuilder.Append(System.IO.File.ReadAllText(stringArray[i])); 
    }
     string bulidOutput = stringBuilder.ToString();    
     string newFilePath = @"C:\NewMergeFileName.txt";
    System.IO.File.WriteAllText(newFilePath, bulidOutput);

     is there any other way which is better/faster/more concise doing this?

  1. C G E Mannerheim

    Post:29

    Points:203
    Re: Merge many text files into single text file using C#?

    using (var bulidOutput = File.Create("bulidOutput"))
    {
        foreach (var file in new[] { "firstFile", "secondFile" })
        {
            using (var input = File.OpenRead(file))
            {
                input.CopyTo(bulidOutput);
            }
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!