Search code examples
c#performanceconcatenation

Efficient way to combine multiple text files


I have multiple files of text that I need to read and combine into one file. The files are of varying size: 1 - 50 MB each. What's the most efficient way to combine these files without bumping into the dreading System.OutofMemoryException?


Solution

  • Darin is on the right track. My tweak would be:

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