Read and Write Binary file: int, string : Binary File Read « File Directory « VB.Net






Read and Write Binary file: int, string

Read and Write Binary file: int, string
  
Imports System.IO

Module Module1

    Sub Main()
        Dim Stream As FileStream
        Try
            Stream = New FileStream("test.dat", FileMode.Create)
        Catch E As Exception
            Console.WriteLine("Error creating test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try

        Dim BinaryStream As New BinaryWriter(Stream)

        Dim Age As Integer = 21
        Dim Salary As Double = 100000.0
        Dim Name As String = "Joe"

        Try
            BinaryStream.Write(Age)
            BinaryStream.Write(Salary)
            BinaryStream.Write(Name)
            BinaryStream.Close()

            Console.WriteLine("Data written to test.Dat")
        Catch E As Exception
            Console.WriteLine("Error writing to test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try
        
        'Read 
        
        Try
            Stream = New FileStream("test.dat", FileMode.Open)
        Catch E As Exception
            Console.WriteLine("Error opening test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try

        Dim BinaryStreamReader As New BinaryReader(Stream)

        Try
            Age = BinaryStreamReader.ReadInt32()
            Salary = BinaryStreamReader.ReadDouble()
            Name = BinaryStreamReader.ReadString()
            BinaryStreamReader.Close()

            Console.WriteLine("Age: {0}", Age)
            Console.WriteLine("Salary: {0}", Salary)
            Console.WriteLine("Name: {0}", Name)
        Catch E As Exception
            Console.WriteLine("Error reading to test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try

    End Sub

End Module


           
         
    
  








Related examples in the same category

1.Reading a sequential-access fileReading a sequential-access file
2.Read from a binary fileRead from a binary file
3.Check Files Are Identical
4.BinaryReader.Read reads the specified number of characters from the stream
5.BinaryReader.ReadByte reads the next byte from the current stream
6.BinaryReader.ReadBytes reads the specified number of bytes
7.BinaryReader.ReadChar reads the next character from the stream