Read Big TXT File, Out of Memory Exception

前端 未结 4 1687
孤独总比滥情好
孤独总比滥情好 2020-11-29 12:19

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\' });
         


        
4条回答
  •  [愿得一人]
    2020-11-29 12:32

    Edit:

    loading the whole file in memory will be causing objects to grow, and .net will throw OOM exceptions if it cannot allocate enough contiguous memory for an object.

    The answer is still the same, you need to stream the file, not read the entire contents. That may require a rearchitecture of your application, however using IEnumerable<> methods you can stack up business processes in different areas of the applications and defer processing.


    A "powerful" machine with 8GB of RAM isn't going to be able to store a 500GB file in memory, as 500 is bigger than 8. (plus you don't get 8 as the operating system will be holding some, you can't allocate all memory in .Net, 32-bit has a 2GB limit, opening the file and storing the line will hold the data twice, there is an object size overhead....)

    You can't load the whole thing into memory to process, you will have to stream the file through your processing.

提交回复
热议问题