Writes a length-prefixed string : Binary File Write « File Directory « VB.Net






Writes a length-prefixed string

 

Imports System
Imports System.IO
Imports System.Text

Public Class BinReadWrite
    Public Shared Sub Main()
        Dim testfile As String = "C:\testfile.bin"

        Dim fs As FileStream = File.Create(testfile)
        Dim utf8 As New UTF8Encoding()

        Dim bw As New BinaryWriter(fs, utf8)
        Dim bstring As String

        bstring  = "this is a test" + vbNewLine
        bw.Write(bstring)

        fs.Seek(0, SeekOrigin.Begin)

        Dim len As Integer = fs.ReadByte() And 127
        len = len + fs.ReadByte() * 128
        Dim rawbytes(len) As Byte
        fs.Read(rawbytes, 0, len)

        Console.WriteLine(utf8.GetString(rawbytes))

        fs.Seek(0, SeekOrigin.Begin)

        Dim br As New BinaryReader(fs, utf8)
        bstring = br.ReadString()
        Console.WriteLine(bstring)
        fs.Close()
    End Sub
End Class

   
  








Related examples in the same category

1.Creating a random file
2.Use BinaryWriter to store information into a binary file
3.Save Structure to a Binary File
4.Gets the underlying stream of the BinaryWriter.
5.BinaryWriter.Seek Method Sets the position within the current stream.
6.BinaryWriter.Write Method Writes an unsigned byte to the current stream and advances the stream position by one byte.
7.BinaryWriter.Write(Byte[]) Writes a byte array to the underlying stream.
8.Writes a region of a byte array to the current stream.
9.Writes a Unicode character
10.Writes a character array
11.Writes a section of a character array