MemoryStream Class in VB.NET

In this article I will explain you about MemoryStream Class in VB.NET.
  • 15463

MemoryStream Class:  A memory stream is created from an array of unsigned bytes rather than from a file or other stream. Memory streams are used as temporary, in-memory storage (temporary buffers) in lieu of creating temporary files. This stream is highly optimized for speed since the data is stored in memory and the processor can easily access it. Memory streams should be used to store frequently accessed data.

The Read and Write methods of the MemoryStream class read and write from an internal buffer that is created when the memory stream is created. The example shown in Listing 6.9 uses the MemoryStream class to add a custom signature at the end of the specified file.

Listing 6.9: MemoryStream Reading and Writing Example

Imports System
Imports System.IO
Imports System.Text
Public Class MemStream
    Public Shared Sub Main(ByVal args As String())
        'Check the number or arguments
        If args.Length < 1 Then
            Console.WriteLine("Usage: MemStream <sourcefile>")
        End If
            'Get the current date
            Dim dt As DateTime = DateTime.Now
            Dim tag As String = "This file was signed on " + dt.ToShortDateString()
            'Get a byte array from the string
            Dim tagarray As Byte() = System.Text.Encoding.ASCII.GetBytes(tag.ToCharArray())
            'Construct a memory stream with the byte
            'array as a parameter
            Dim mstream As New MemoryStream(tagarray)
            'Open a FileStream on the source file
            Dim fout As New FileStream(args(0), FileMode.Open, FileAccess.Write)
            'Seek to the end of the file
            fout.Seek(0, SeekOrigin.[End])
            Dim buffer As [Byte]() = New [Byte](tagarray.Length) {}
            Console.WriteLine("Starting to write signature")
            'Read the contents of the MemoryStream into a buffer
            Dim n As Integer = mstream.Read(buffer, 0, buffer.Length
            'Write the buffer to the file
            fout.Write(buffer, 0, n)
            'Close the streams
            Console.WriteLine("Signature Written")
        Catch e As IOException
            Console.WriteLine("An IO Exception Occurred :", e)
        Catch oe As Exception
            Console.WriteLine("An Exception Occurred :", oe)
        End Try
    End Sub
End Class

In this example, a MemoryStream object is created and a byte arrayâ€"containing signature is stored in the memory stream's buffer. Then a file stream is opened on the source file and the Seek method is used to seek to the end of the file. Once positioned at the end of the file, the code gets the contents of the memory stream and writes the contents to the file stream.


Hope this article would have helped you in understanding MemoryStream Class in VB.NET.


More Articles

© 2020 DotNetHeaven. All rights reserved.