use*_*769 33
我支持Mehrdad Afshari,他的代码与System.IO.Stream.CopyTo中的代码完全相同.我仍然想知道他为什么不使用相同的功能而不是重写它的实现.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据反汇编程序(ILSpy),默认缓冲区大小为4096.CopyTo函数有一个重载,它允许您指定缓冲区大小,以防您对4096字节不满意.
Meh*_*ari 25
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);
Run Code Online (Sandbox Code Playgroud)
如果你的文件是文本而不是很大,那么就可以说一些简单明了的代码.我会使用以下内容.
File.ReadAllText("file1") + File.ReadAllText("file2") + File.ReadAllText("file3");
Run Code Online (Sandbox Code Playgroud)
如果您的文件是大文本文件并且您在Framework 4.0上,则可以使用File.ReadLines以避免缓冲整个文件.
File.WriteAllLines("out", new[] { "file1", "file2", "file3" }.SelectMany(File.ReadLines));
Run Code Online (Sandbox Code Playgroud)
如果您的文件是二进制文件,请参阅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();
Run Code Online (Sandbox Code Playgroud)