MEMORYSTREAM

Like FileStream, the MemoryStream class inherits from the Stream class. This class represents a stream with data stored in memory. Like the FileStream, it provides only relatively primitive methods for reading and writing data. Usually, you will want to attach a higher-level object to the MemoryStream to make using it easier.

Example program MemoryStreamWrite uses the following code to write and read from a MemoryStream object:

Dim memory_stream As New MemoryStream()
Dim binary_writer As New BinaryWriter(memory_stream)
binary_writer.Write("Peter Piper picked a peck of pickled peppers.")
 
Dim binary_reader As New BinaryReader(memory_stream)
memory_stream.Seek(0, SeekOrigin.Begin)
MessageBox.Show(binary_reader.ReadString())
binary_reader.Close()

This program first creates the MemoryStream. It then creates a BinaryWriter attached to the MemoryStream and uses it to write some text into the stream. Next, the program makes a BinaryReader object attached to the same MemoryStream. It uses the stream’s Seek method to rewind the stream to its beginning, and then uses the BinaryReader’s ReadString method to read the string out of the MemoryStream.

The following example does the same things as the previous example, except it uses the StreamWriter and StreamReader classes instead of BinaryWriter and BinaryReader. Note that this version must call the StreamWriter class’s Flush method to ensure that all of the text is written into the MemoryStream before it can read the memory using ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.