File.WriteAllText Out Of Memory Exception On Large Strings

by StoneJunction 7. October 2011 20:17

I ran into a problem yesterday with the File.WriteAllText method when saving large text files to disk. 

 

I had a piece of code similar to this:

	public void Test(List<String> lines)
        {
            var output = new StringBuilder();
            foreach (String line in lines)
            {
                output.Append(line).Append(Environment.NewLine);
            }
 
            File.WriteAllText(@"c:\test.txt", output.ToString());
        }

which worked fine for small string lists. However when the list of strings ran to the 100's of Mb I got System Out of Memory errors. A simple google seemed to show a few people with similar problems but no real solutions. Pushed for time I copped out and replaced it with a good old fashioned StreamWriter:

 

	public void Test(List<String> lines)
        {
            var file = new StreamWriter(@"c:\test.txt");
            foreach (String line in lines)
            {
                file.WriteLine(line);
            }
 
            file.Close();
        }

 

Tags: , , ,

Programming | C#

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading