在C#中连接三个文件的最快方法是什么?

我需要使用C#连接3个文件。 头文件,内容和页脚文件,但我想这样做很酷。

酷=非常小的代码或非常快(非汇编代码)。

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); 

我支持Mehrdad Afshari,他的代码与System.IO.Stream.CopyTo中的代码完全相同。 我仍然想知道他为什么不使用相同的function而不是重写它的实现。

  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); } } } 

根据反汇编程序( ILSpy ),默认缓冲区大小为4096. CopyTo函数有一个重载,它允许您指定缓冲区大小,以防您对4096字节不满意。

如果你的文件是文本而不是很大,那么对于简单明了的代码来说,有一些东西可以说。 我会使用以下内容。

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

如果您的文件是大文本文件而且您使用的是Framework 4.0,则可以使用File.ReadLines来避免缓冲整个文件。

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

如果您的文件是二进制文件,请参阅Mehrdad的答案

另一种方式……让操作系统为你做这件事怎么样?:

 ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", String.Format(@" /c copy {0} + {1} + {2} {3}", file1, file2, file3, dest)); psi.UseShellExecute = false; Process process = Process.Start(psi); process.WaitForExit(); 

你的意思是3个文本文件? 结果是否需要再次成为文件?

怎么样的:

 string contents1 = File.ReadAllText(filename1); string contents2 = File.ReadAllText(filename2); string contents3 = File.ReadAllText(filename3); File.WriteAllText(outputFileName, contents1 + contents2 + contents3); 

当然,使用StringBuilder和一些额外的智能,您可以轻松扩展它以处理任意数量的输入文件:-)

干杯

如果您在Win32环境中,最有效的解决方案可能是使用Win32 API函数“WriteFile”。 VB 6中有一个例子 ,但用C#重写它并不困难。

我不太了解C# – 你可以从那里调用shell吗? 你能做点什么吗?

  system("type file1 file2 file3 > out"); 

我相信渐渐地,这应该是非常快的。