Necesito hacer StreamWriter.flush()?


Supongamos que este código C#:

using (MemoryStream stream = new MemoryStream())
{
    StreamWriter normalWriter = new StreamWriter(stream);
    BinaryWriter binaryWriter = new BinaryWriter(stream);

    foreach(...)
    {
        binaryWriter.Write(number);
        normalWriter.WriteLine(name); //<~~ easier to reader afterward.
    }

    return MemoryStream.ToArray();
}

Mis preguntas son:

  1. ¿Necesito usar flush dentro del bucle para preservar el orden?
  2. ¿Es legal regresar MemoryStream.ToArray()? Yo usando el bloque using como una convención, me temo que arruinará las cosas.
Author: H. Pauwelyn, 2009-06-29

2 answers

Borra la respuesta anterior: no me había dado cuenta de que estabas usando dos envoltorios alrededor de la misma corriente. Eso me parece un poco arriesgado.

De cualquier manera, pondría el StreamWriter y BinaryWriter en sus propios bloques using.

Ah, y sí, es legal llamar a ToArray() en el MemoryStream - los datos se conservan incluso después de que se eliminan.

Si realmente quieres usar las dos envolturas, lo haría así: {[12]]}

using (MemoryStream stream = new MemoryStream())
{
    using (StreamWriter normalWriter = new StreamWriter(stream))
    using (BinaryWriter binaryWriter = new BinaryWriter(stream))
    {
        foreach(...)
        {
            binaryWriter.Write(number);
            binaryWriter.Flush();
            normalWriter.WriteLine(name); //<~~ easier to read afterward.
            normalWriter.Flush();
        }
    }    
    return MemoryStream.ToArray();
}

Tengo que decir, soy un poco cauteloso de usar dos envoltorios alrededor la misma corriente sin embargo. Tendrá que seguir limpiando cada uno de ellos después de cada operación para asegurarse de que no termine con datos extraños. Usted podría establecer el StreamWriter ' s AutoFlush propiedad de true para mitigar la situación, y yo creo que BinaryWriter actualmente no en realidad requiere descarga (es decir, no almacena ningún dato), pero confiar en que se siente arriesgado.

Si tienes que mezclar datos binarios y de texto, usaría un BinaryWriter y escribiría explícitamente los bytes para la cadena, buscar con Encoding.GetBytes(string).

 24
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 16:34:46

Update

No importa esta respuesta, me confundí con los escritores...


  1. No, el orden se conservará (actualizar: tal vez no). Flush es útil / necesario en otras situaciones, aunque no puedo recordar cuándo.
  2. Creo que sí, usando se asegura de que todo se limpie bien.
 0
Author: mbillard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-29 18:40:15