Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a string from a MemoryStream?

If I am given a MemoryStream that I know has been populated with a String, how do I get a String back out?

like image 868
Brian Avatar asked Sep 16 '08 23:09

Brian


People also ask

How do you turn a stream into a string?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.

How do I get bytes from MemoryStream?

To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.

How do I reuse MemoryStream?

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.


1 Answers

This sample shows how to read and write a string to a 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 
like image 177
Brian Avatar answered Sep 28 '22 05:09

Brian