Si on me donne un MemoryStream
qui a été rempli avec un String
, comment puis-je récupérer un String
?
Réponses
Trop de publicités?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();
}
Coderer
Points
5099
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
Darren Kopp
Points
27704
utilisez un StreamReader , vous pouvez utiliser la méthode ReadToEnd qui renvoie une chaîne.
Arek Bal
Points
180