The out of memory error may be caused by any number of reasons, based on how Windows virtual memory and how the .NET runtime works.
Do you really need to dump everything into the StringBuilder all at once? If you're writing to a file, you can do the operation in pieces at a time.
Use something like this as a starting point: int bufferSize = 65536;
using (StreamWriter sw = new StreamWriter("filename", true, System.Text.Encoding.UTF8, bufferSize))
{
while(!finished)
{
string data = "foo"; //get next data here...
sw.Write(data);
}
}
`