gpt4 book ai didi

c# - 读取大 TXT 文件,内存不足异常

转载 作者:可可西里 更新时间:2023-11-01 03:13:15 30 4
gpt4 key购买 nike

我想阅读大 TXT 文件,大小为 500 MB,首先我使用

var file = new StreamReader(_filePath).ReadToEnd();  
var lines = file.Split(new[] { '\n' });

但它抛出内存异常,然后我尝试逐行读取,但在读取大约 150 万行后再次抛出内存异常

  using (StreamReader r = new StreamReader(_filePath))
{
while ((line = r.ReadLine()) != null)
_lines.Add(line);
}

或者我用过

  foreach (var l in File.ReadLines(_filePath))
{
_lines.Add(l);
}

但是我又收到了

An exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll but was not handled in user code

我的机器功能强大,有 8GB 内存,所以这不应该是我的机器问题。

p.s: 我试图在 NotePadd++ 中打开这个文件,但我收到了“文件太大而无法打开”的异常。

最佳答案

只需使用 File.ReadLines返回 IEnumerable<string>并且不会一次将所有行加载到内存中。

foreach (var line in File.ReadLines(_filePath))
{
//Don't put "line" into a list or collection.
//Just make your processing on it.
}

关于c# - 读取大 TXT 文件,内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13415916/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com