有效的方式来合并多个文本文件 [英] Efficient way to combine multiple text files
本文介绍了有效的方式来合并多个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个文本文件,我需要阅读,并结合成一个文件。
的文件是不同大小的:1 - 每50 MB。
什么是这些文件没有撞到害怕结合最有效的方式的System.OutOfMemoryException
?
I have multiple files of text that I need to read and combine into one file.
The files are of varying size: 1 - 50 MB each.
What's the most efficient way to combine these files without bumping into the dreading System.OutofMemoryException
?
推荐答案
做到在块:
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);
}
}
}
}
这篇关于有效的方式来合并多个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文