566 votes

Comment obtenez-vous une chaîne à partir d'un MemoryStream?

Si on me donne un MemoryStream qui a été rempli avec un String , comment puis-je récupérer un String ?

479voto

Brian Points 13596

Cet exemple montre comment lire et écrire une chaîne dans un MemoryStream.


 static void Main(string[] args)
{
    using (var ms = new MemoryStream())
    {
        var sw = 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
        //DON'T DO THIS - 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;
        var sr = new StreamReader(ms);
        var myStr = sr.ReadToEnd();
        Console.WriteLine(myStr);
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}
 

347voto

Coderer Points 5099

Vous pouvez aussi utiliser

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

Je ne pense pas que ce soit moins efficace, mais je ne pouvais pas jurer de le faire. Il vous permet également de choisir un encodage différent, alors qu'avec StreamReader vous devez le spécifier en tant que paramètre.

103voto

Brian Points 13596

Utilisation d'un StreamReader pour convertir le MemoryStream en chaîne.

 <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
 

44voto

Darren Kopp Points 27704

utilisez un StreamReader , vous pouvez utiliser la méthode ReadToEnd qui renvoie une chaîne.

26voto

Arek Bal Points 180

Les solutions précédentes ne fonctionnerait pas dans les cas où l’encodage est impliqué. Voici exemple - type d’une « vraie vie » - comment le faire correctement...

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X