Write StringBuilder to Stream

Andy Joiner picture Andy Joiner · Feb 10, 2010 · Viewed 83.7k times · Source

What is the best method of writing a StringBuilder to a System.IO.Stream?

I am currently doing:

StringBuilder message = new StringBuilder("All your base");
message.Append(" are belong to us");

System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
stream.Write(encoder.GetBytes(message.ToString()), 0, message.Length);

Answer

Neil Barnwell picture Neil Barnwell · Feb 10, 2010

Don't use a StringBuilder, if you're writing to a stream, do just that with a StreamWriter:

using (var memoryStream = new MemoryStream())
using (var writer = new StreamWriter(memoryStream ))
{
    // Various for loops etc as necessary that will ultimately do this:
    writer.Write(...);
}