17

I need to create a large text document. I currently use StringBuilder to make the document and then call File.WriteallText(filename,sb.ToString). Unfortunately, this is now starting to throw out of memory exceptions.

Is there a better way to stream a StringBuilder to file or is there some other technique I should be using?

gonzobrains
  • 7,856
  • 14
  • 81
  • 132
GreyCloud
  • 3,030
  • 5
  • 32
  • 47
  • 1
    Could you not just do File.WriteAllText with the text you are adding rather than putting into a stringbuilder and doing it all at once? – Bali C Nov 04 '11 at 10:50
  • 3
    @Bali to call `WriteAllText` you need to have all the text, so that won't help with memory issues – Marc Gravell Nov 04 '11 at 10:54

4 Answers4

23

Instead of using StringBuilder, try using TextWriter (which has a broadly similar API, but which can write to a number of underlying destinations, including files) - i.e.

using(TextWriter writer = File.CreateText(path))
{
    // loop etc
    writer.Write(...);
}

More generally, it is worth separating the code that knows about files from the code that knows about how to write the data, i.e.

using(var writer = File.CreateText(path))
{
    Serialize(writer);
}
...
void Serialize(TextWriter writer)
{
    ...
}

this makes it easier to write to different targets. For example, you can now do in-memory too:

var sw = new StringWriter();
Serialize(sw);
string text = sw.ToString();

The point being: your Serialize code didn't need to change to accomodate a different target. This could also be writing directly to a network, or writing through a compression/encryption stream. Very versatile.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5

Just use a StreamWriter that writes to a FileStream:

using (StreamWriter writer = new StreamWriter("filename.txt")) {
  ...
}

This will of course mean that you can't change the text that is already written, like you can do in a StringBuilder, but I assume that you are not using that anyway.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer. – Guffa Feb 22 '16 at 18:34
1

Why not streaming directly into the stream? You could use the TextWriter.

Simon
  • 1,496
  • 8
  • 11
0

You can use StreamWriter and write to the file directly.

ElDog
  • 1,230
  • 1
  • 10
  • 21