Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the fastest way to concatenate three files in C#?

Tags:

c#

file

I need to concatenate 3 files using C#. A header file, content, and a footer file, but I want to do this as cool as it can be done.

Cool = really small code or really fast (non-assembly code).

like image 696
Bobby Bruckovnic Avatar asked Jan 14 '09 19:01

Bobby Bruckovnic


3 Answers

I support Mehrdad Afshari on his code being exactly same as used in System.IO.Stream.CopyTo. I would still wonder why did he not use that same function instead of rewriting its implementation.

string[] srcFileNames = { "file1.txt", "file2.txt", "file3.txt" };
string destFileName = "destFile.txt";

using (Stream destStream = File.OpenWrite(destFileName))
{
    foreach (string srcFileName in srcFileNames)
    {
        using (Stream srcStream = File.OpenRead(srcFileName))
        {
            srcStream.CopyTo(destStream);
        }
    }
}

According to the disassembler (ILSpy) the default buffer size is 4096. CopyTo function has got an overload, which lets you specify the buffer size in case you are not happy with 4096 bytes.

like image 195
user664769 Avatar answered Oct 19 '22 04:10

user664769


void CopyStream(Stream destination, Stream source) {
   int count;
   byte[] buffer = new byte[BUFFER_SIZE];
   while( (count = source.Read(buffer, 0, buffer.Length)) > 0)
       destination.Write(buffer, 0, count);
}


CopyStream(outputFileStream, fileStream1);
CopyStream(outputFileStream, fileStream2);
CopyStream(outputFileStream, fileStream3);
like image 45
mmx Avatar answered Oct 19 '22 03:10

mmx


If your files are text and not large, there's something to be said for dead-simple, obvious code. I'd use the following.

File.ReadAllText("file1") + File.ReadAllText("file2") + File.ReadAllText("file3");

If your files are large text files and you're on Framework 4.0, you can use File.ReadLines to avoid buffering the entire file.

File.WriteAllLines("out", new[] { "file1", "file2", "file3" }.SelectMany(File.ReadLines));

If your files are binary, See Mehrdad's answer

like image 7
Jimmy Avatar answered Oct 19 '22 02:10

Jimmy