[問題] 請問文字檔太大OutOfMemoryException

作者: takesi5200 (小咪)   2017-12-19 08:34:46
不好意思,我所處理的IO文字檔是未格式化的
文字檔最少有1GB多,差不多有2千多萬行
我用ReadAllLines方式存在string變數裡
但執行確出現"OutOfMemoryException"
不知道有沒有高手可以幫忙~"~ 感謝萬分
DirectoryInfo di = new DirectoryInfo(System.Environment.CurrentDirectory + @"\
tm
List<String> _sub = new List<string>(); //宣告動態陣列
foreach (var fi in di.GetFiles("*", SearchOption.AllDirectories))
{ //tmp資料夾裡的文字檔都做處理
Console.WriteLine("準備中.....");
Console.WriteLine(System.Environment.NewLine);
foreach (string s in System.IO.File.ReadAllLines(di + fi.Name))
{//將檔案內容放置_sub陣列裡
_sub.Add(s);
counter++;
}
}
P.S: 光一個文字檔就有1GB多了;資料量非常龐大...
作者: ssccg (23)   2017-12-19 09:09:00
大檔案不要一次全讀進記憶體啊用Stream一次處理一部分就好
作者: testPtt (測試)   2017-12-19 09:13:00
StreamReader 有試過嗎
作者: Laluth (陽光)   2017-12-19 13:04:00
應該是卡到執行檔使用記憶體的上限 程式改成64bit看看
作者: Litfal (Litfal)   2017-12-19 13:59:00
不是阿,你讀完放到陣列裡面,不就等於放在記憶體裡你文字檔格式是什麼?UTF-8或ANSI讀出來成String變Unicode,單位元組字多的話,讀出來需要的記憶體就翻倍了。1GB檔讀完爆2GB記憶體很正常你可以試試用.nf 4.5以上的64bit,或是改寫你每一行處理的邏輯
作者: capercat (Qoo)   2017-12-19 16:27:00
搜尋 gcAllowVeryLargeObject 這個試試
作者: cancelpc (阿吉)   2017-12-19 18:44:00
改一次讀單列,或 stream 方式處理。剛看到 readline 也有問題!你單列處理完有釋放嗎?還是一直 add 那還不是都放在 memory 裡

Links booklink

Contact Us: admin [ a t ] ucptt.com