¿Cómo se obtiene una cadena de un MemoryStream?

Resuelto Brian asked hace 16 años • 14 respuestas

Si me dan un formulario MemoryStreamque sé que se ha completado con un String, ¿cómo puedo recuperarlo String?

Brian avatar Sep 17 '08 06:09 Brian
Aceptado

Este ejemplo muestra cómo leer y escribir una cadena en un MemoryStream.


Imports System.IO

Module Module1
  Sub Main()
    ' We don't need to dispose any of the MemoryStream 
    ' because it is a managed object. However, just for 
    ' good practice, we'll close the MemoryStream.
    Using ms As New MemoryStream
      Dim sw As New StreamWriter(ms)
      sw.WriteLine("Hello World")
      ' The string is currently stored in the 
      ' StreamWriters buffer. Flushing the stream will 
      ' force the string into the MemoryStream.
      sw.Flush()
      ' If we dispose the StreamWriter now, it will close 
      ' the BaseStream (which is our MemoryStream) which 
      ' will prevent us from reading from our MemoryStream
      'sw.Dispose()

      ' The StreamReader will read from the current 
      ' position of the MemoryStream which is currently 
      ' set at the end of the string we just wrote to it. 
      ' We need to set the position to 0 in order to read 
      ' from the beginning.
      ms.Position = 0
      Dim sr As New StreamReader(ms)
      Dim myStr = sr.ReadToEnd()
      Console.WriteLine(myStr)

      ' We can dispose our StreamWriter and StreamReader 
      ' now, though this isn't necessary (they don't hold 
      ' any resources open on their own).
      sw.Dispose()
      sr.Dispose()
    End Using

    Console.WriteLine("Press any key to continue.")
    Console.ReadKey()
  End Sub
End Module
Brian avatar Sep 29 '2008 18:09 Brian

También puedes usar

Encoding.ASCII.GetString(ms.ToArray());

No creo que esto sea menos eficiente, pero no podría jurarlo. También le permite elegir una codificación diferente, mientras que al usar un StreamReader tendría que especificarla como parámetro.

Coderer avatar Oct 24 '2008 16:10 Coderer

Usando un StreamReader para convertir MemoryStream en una cadena.

<Extension()> _
Public Function ReadAll(ByVal memStream As MemoryStream) As String
    ' Reset the stream otherwise you will just get an empty string.
    ' Remember the position so we can restore it later.
    Dim pos = memStream.Position
    memStream.Position = 0

    Dim reader As New StreamReader(memStream)
    Dim str = reader.ReadToEnd()

    ' Reset the position so that subsequent writes are correct.
    memStream.Position = pos

    Return str
End Function
Brian avatar Sep 16 '2008 23:09 Brian