I have a created a StringBuilder
of length "132370292", when I try to get the string using the ToString()
method it throws OutOfMemoryException
.
StringBuilder SB = new StringBuilder();
for(int i =0; i<=5000; i++)
{
SB.Append("Some Junk Data for testing. My Actual Data is created from different sources by Appending to the String Builder.");
}
try
{
string str = SB.ToString(); // Throws OOM mostly
Console.WriteLine("String Created Successfully");
}
catch(OutOfMemoryException ex)
{
StreamWriter sw = new StreamWriter(@"c:\memo.txt", true);
sw.Write(SB.ToString()); //Always writes to the file without any error
Console.WriteLine("Written to File Successfully");
}
What is the reason for the OOM while creating a new string and why it doesn't throw OOM while writing to a file?
Machine Details: 64-bit, Windows-7, 2GB RAM, .NET version 2.0
mytext
? And why are you writing to aStringBuilder
if and then to a stream? Why no the stream directly using aStringWriter
? – Oreganosw
) cumulatively - not building the entire thing in memory. (/cc @DebugErr just to note that this is 252MB, not 126MB) – Announcer