[C#] 'System.OutOfMemoryException' 的例外狀況
問題描述:
當我使用「Encoding.UTF8.GetString(bytes)」方法,想將FTP接回來的byte[]轉回txt文字內容時,發生了「'System.OutOfMemoryException' 的例外狀況」(如下圖)。
ps:遠端的這個txt檔確很大,有好幾MB。
解決方法:
這個問題的發生原因似乎是因為字符串在 .NET 中始終是 unicode,因此 ASCII 字節數組將轉換為需要 676 MB 內存的字符串(建議使用GetString()方法時不要超過10MB)。
我的解決方法是先new 一個MemoryStream,用StreamReader將byte array裝進去後,再ReadLine(),一行一行讀,改成用 List 去裝 每行的資料。
code:
 var path = @"D:\桌面\1.txt";
            var bytesFromFile = System.IO.File.ReadAllBytes(path);
            //原始方法
            var str = Encoding.UTF8.GetString(bytesFromFile);
            //改成用 List 去裝 每行的資料
            var list= new List<string>();
            using (Stream stream = new MemoryStream(bytesFromFile))
            {
                using (StreamReader sr = new StreamReader(stream))
                {
                    var line = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        var value = line.Replace("\r\n", string.Empty);
                        list.Add(value);
                    }                
                }
            }
留言
張貼留言