Pregunta

¿Cuál es el mejor método de escritura de un StringBuilder a un System.IO.Stream?

Actualmente estoy haciendo:

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);
¿Fue útil?

Solución

No utilice un StringBuilder, si usted está escribiendo a un arroyo, hacer eso con un 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(...);
}

Otros consejos

Este es el mejor método. Otras pérdidas sabia el StringBuilder y usar algo como lo siguiente:

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

Tal vez sea útil.

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

En función de su caso de uso también puede tener sentido para empezar sólo con un 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

Si desea utilizar algo así como un StringBuilder porque es más limpio para pasar alrededor y trabajar con él, entonces se puede usar algo como el siguiente alternativo StringBuilder creé.

Lo más importante que lo hace diferente es que permite el acceso a los datos internos sin tener que montar en una cadena o ByteArray primero. Esto significa que usted no tiene que duplicar los requisitos de memoria y correr el riesgo de intentar asignar un trozo contiguo de memoria que se adapte a todo el objeto.

NOTA: Estoy seguro de que hay mejores opciones a continuación, utilizando un List<string>() internamente pero esto era simple y resultó ser lo suficientemente bueno para mis propósitos

.
public class StringBuilderEx
{
    List<string> data = new List<string>();
    public void Append(string input)
    {
        data.Add(input);
    }
    public void AppendLine(string input)
    {
        data.Add(input + "\n");
    }
    public void AppendLine()
    {
        data.Add("\n");
    }

    /// <summary>
    /// Copies all data to a String.
    /// Warning: Will fail with an OutOfMemoryException if the data is too
    /// large to fit into a single contiguous string.
    /// </summary>
    public override string ToString()
    {
        return String.Join("", data);
    }

    /// <summary>
    /// Process Each section of the data in place.   This avoids the
    /// memory pressure of exporting everything to another contiguous
    /// block of memory before processing.
    /// </summary>
    public void ForEach(Action<string> processData)
    {
        foreach (string item in data)
            processData(item);
    }
}

Ahora se puede volcar todo el contenido de presentar usando el siguiente código.

var stringData = new StringBuilderEx();
stringData.Append("Add lots of data");

using (StreamWriter file = new System.IO.StreamWriter(localFilename))
{
    stringData.ForEach((data) =>
    {
        file.Write(data);
    });
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top