C# Very Large String Manipulation (Out of Memory Exception)

后端 未结 5 1021
别跟我提以往
别跟我提以往 2021-01-17 10:32

I have a need to read in a 1gb raw text file from disk to ram to do some string manipulation in C#.

string contents = File.ReadAllText(path)
<
5条回答
  •  無奈伤痛
    2021-01-17 11:18

    I was using ReadAllText for 109 mb file and was getting out of memory which is really odd. Anyway, so I used buffer to read file with good performance and StringBuilder to make it memory efficient. Here is my code:

                    StringBuilder sb = new StringBuilder();
                    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    using (BufferedStream bs = new BufferedStream(fs))
                    using (StreamReader sr = new StreamReader(bs))
                    {
                        string line;                    
                        while ((line = sr.ReadLine()) != null)
                            sb.AppendLine(line);
                    }
    

提交回复
热议问题