views:

637

answers:

2

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);
+5  A: 

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(...);
}
Neil Barnwell
It's not feasible if he needs to use the string for something else before writing it though.
Skurmedel
Absolutely true, but of course he hasn't said that's a requirement, so I didn't make any assumptions.
Neil Barnwell
+2  A: 

That is the best method. Other wise loss the StringBuilder and use something like following

        using (MemoryStream ms = new MemoryStream()) {
            using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode)) {
                sw.WriteLine("dirty world.");
            }
            //do somthing with ms
        }
affan