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 simple methods for reading and writing data. Usually, you will want to attach a higher-level object to the MemoryStream to make using it easier.

The following code creates a MemoryStream object. It then creates a BinaryWriter attached to the MemoryStream and uses it to write some text into the stream. Next, the program creates 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 object’s ReadString method to read the string out of the MemoryStream.

  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() 

The following example does the same things as the previous example, except that 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 




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net