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 the StreamReader.

Using memory_stream As New MemoryStream()
    Dim stream_writer As New StreamWriter(memory_stream)
    stream_writer.Write("Peter Piper picked a peck of pickled peppers.")
    stream_writer.Flush()
 
    Dim stream_reader As New StreamReader(memory_stream)
    memory_stream.Seek(0, SeekOrigin.Begin)
    MessageBox.Show(stream_reader.ReadToEnd())
    stream_reader.Close()
End Using
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.239.155