Search code examples
c#streamstringbuilder

Write StringBuilder to Stream


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);

Solution

  • 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(...);
    }