我需要用C#串联三个文件,包括一个头文件、内容文件和一个脚注文件,但我希望能够以最酷的方式来完成它。
"酷"指的是代码尽可能地小或者非汇编代码运行速度非常快。
"酷"指的是代码尽可能地小或者非汇编代码运行速度非常快。
我支持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);
}
}
}
根据反汇编器(ILSpy)显示,默认缓冲区大小为4096。但是,CopyTo函数有一个重载,允许在不满意4096字节的情况下指定缓冲区大小。
srcStream
吗? - rraallvvusing
时,就像OP在他的答案中写的那样,它会自动清理。 - bugybunnyvoid 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);
ReadAllText
绝对不是正确的选择,因为在将它们读入字符串时可能会破坏文件内容。性能方面暂且不论。 - Mehrdad Afshari如果您的文件是文本且不是很大,那么可以考虑使用简单明了的代码。我建议使用以下代码。
File.ReadAllText("file1") + File.ReadAllText("file2") + File.ReadAllText("file3");
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();
string contents1 = File.ReadAllText(filename1);
string contents2 = File.ReadAllText(filename2);
string contents3 = File.ReadAllText(filename3);
File.WriteAllText(outputFileName, contents1 + contents2 + contents3);