浏览大TXT文件,内存溢出异常异常、内存、文件、TXT

2023-09-03 05:34:11 作者:以前玩游戏都用电脑,现在在手机上就可以玩游戏,很方便,等车或

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

I want to read big TXT file size is 500 MB, First I use

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

但它抛出内存异常了,然后我试过,但看过之后大约150万行再次逐行读取它扔出去的内存异常

but it throw out of memory Exception then I tried to read line by line but again after reading around 1.5 million lines it throw out of memory Exception

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

或者我用

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

但我又收到

类型System.OutOfMemoryException的异常发生   mscorlib.dll中,但没有在用户code处理

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

我的机器是功能强大的机器的RAM 8GB所以它不应该是我的机器的问题。

My Machine is powerful machine with 8GB of ram so it shouldn't be my machine problem.

PS:我试图在NotePadd打开此文件++和我收到'文件过大,无法打开例外

p.s: I tried to open this file in NotePadd++ and I received 'the file is too big to be opened' exception.

推荐答案

只需使用 File.ReadLines 返回一个的IEnumerable<字符串> 并不会一次加载所有的线对内存

Just use File.ReadLines which returns an IEnumerable<string> and doesn't load all the lines at once to the memory.

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