Write StringBuilder to Stream
Depending on your use case it may also make sense to just start with a StringWriter:
StringBuilder sb = null;
// StringWriter - a TextWriter backed by a StringBuilder
using (var writer = new StringWriter())
{
writer.WriteLine("Blah");
. . .
sb = writer.GetStringBuilder(); // Get the backing StringBuilder out
}
// Do whatever you want with the StringBuilder
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(...);
}
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
}
Perhaps it will be usefull.
var sb= new StringBuilder("All your money");
sb.Append(" are belong to us, dude.");
var myString = sb.ToString();
var myByteArray = System.Text.Encoding.UTF8.GetBytes(myString);
var ms = new MemoryStream(myByteArray);
// Do what you need with MemoryStream