我有一个奇怪的问题,我似乎找不到解决办法。我试图用800万行的块读取大文件(从500 of到2Gb)。
为此,我创建了以下内容:
public static List<string> read_file(string path, Int32 start, Int32 end, Boolean is_big_file)
{
try
{
List<string> lines = new List<string>();
if (is_big_file)
lines = File.ReadLines(path).Skip(start).Take(end - start).ToList();
else
lines = File.ReadAllLines(path).ToList();
return lines;
}
catch { return null; }
}如果该文件的行数少于8M,则使用ReadAllLines,所有操作都正常。如果该文件超过此值,它将使用ReadLines.Skip.Take。
第一个块工作,我收到前8M行。开始= 0。结束=8 000 000。
第二块不起作用。start = 8,000,000end = 16,000,000或文件的最后一行(取决于行数)。由于某种原因,当我只有不到800万行可读时(结束= 12,500,000),我就会得到OutOfMemoryException。
你知道为什么会这样吗?Skip也缓存原始行吗?有更优雅的解决方案吗?
谢谢!
发布于 2015-01-01 10:25:19
实际上,用这个:
File.ReadLines(path)您正在阅读所有的行。您最好对要读取的字节使用FileStream和Seek。就像这样:
using (FileStream fs = new FileStream(path, FileMode.Open))
{
fs.Seek(start, SeekOrigin.Begin);
TextReader tr = new StreamReader(fs);
string line = tr.ReadLine();
}https://stackoverflow.com/questions/27729837
复制相似问题