Dav*_*ing 18 c# performance concatenation
我有多个文本文件需要阅读并合并到一个文件中.这些文件大小不一:每个1到50 MB.什么是组合这些文件而不会陷入恐惧的最有效方法System.OutofMemoryException
?
Dar*_*rov 22
分块做:
const int chunkSize = 2 * 1024; // 2KB
var inputFiles = new[] { "file1.dat", "file2.dat", "file3.dat" };
using (var output = File.Create("output.dat"))
{
foreach (var file in inputFiles)
{
using (var input = File.OpenRead(file))
{
var buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
n8w*_*wrl 22
达林走在正确的轨道上.我的调整是:
using (var output = File.Create("output"))
{
foreach (var file in new[] { "file1", "file2" })
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
Run Code Online (Sandbox Code Playgroud)