【发布时间】:2021-03-25 20:12:53
【问题描述】:
我想读取一个大小为数百 GB 甚至 TB 的 CSV 文件。我有一个限制,我只能读取 32MB 的文件。我对这个问题的解决方案,它不仅工作有点慢,而且还可能在中间断线。
我想问你是否知道更好的解决方案:
const int MAX_BUFFER = 33554432; //32MB
byte[] buffer = new byte[MAX_BUFFER];
int bytesRead;
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
using (BufferedStream bs = new BufferedStream(fs))
{
string line;
bool stop = false;
while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0) //reading only 32mb chunks at a time
{
var stream = new StreamReader(new MemoryStream(buffer));
while ((line = stream.ReadLine()) != null)
{
//process line
}
}
}
请不要回复逐行读取文件的解决方案(例如,File.ReadLines 不是可接受的解决方案)。为什么?因为我只是在寻找另一种解决方案...
【问题讨论】:
-
为什么它不是一个可接受的解决方案?请记住,在您阅读之前,框架不会涉及您正在阅读的文件的内容。