C# version here.
Binary primitives can be written to and read from files directly using the BinaryWriter and BinaryReader classes. You can use these classes to create your own binary file format for your application.
Below is an example that writes some binary primitives to a new file, then reads those values back again and displays them. Each value in the file is preceded by a byte whose value indicates the data type of the following value. You can change the types and values in the writing section of the code below to whatever you want and you'll find that, as long as you specify the correct data type for each value you write, the reading section will always display the correct output.
Create a new Console Application project and then copy the following code over the existing code and then just run the project.Code:Imports System.IO Module Module1 Sub Main() Const filePath As String = "C:\BinaryTest.bin" Using writer As New BinaryWriter(File.Open(filePath, FileMode.Create)) 'Write a 32-bit integer. writer.Write(DataType.Int32) writer.Write(12345) 'Write a double-preceision floating-point value. writer.Write(DataType.Double) writer.Write(222.333) 'Write a string. writer.Write(DataType.String) writer.Write("Hello World") 'Write a 32-bit integer. writer.Write(DataType.Int32) writer.Write(98765) End Using Dim type As DataType Using reader As New BinaryReader(File.OpenRead(filePath)) 'Keep reading while there is data available. Do Until reader.PeekChar() = -1 'Read the data type of the following value. type = DirectCast(reader.ReadByte(), DataType) Console.Write("{0}: ", type) 'Read the next value based on its data type. Select Case type Case DataType.Byte Console.WriteLine(reader.ReadByte().ToString()) Case DataType.Int16 Console.WriteLine(reader.ReadInt16().ToString()) Case DataType.Int32 Console.WriteLine(reader.ReadInt32().ToString()) Case DataType.Int64 Console.WriteLine(reader.ReadInt64().ToString()) Case DataType.Single Console.WriteLine(reader.ReadSingle().ToString()) Case DataType.Double Console.WriteLine(reader.ReadDouble().ToString()) Case DataType.Decimal Console.WriteLine(reader.ReadDecimal().ToString()) Case DataType.String Console.WriteLine(reader.ReadString()) Case DataType.Char Console.WriteLine(reader.ReadChar().ToString()) Case DataType.Boolean Console.WriteLine(reader.ReadBoolean().ToString()) End Select Loop End Using Console.ReadLine() End Sub End Module Public Enum DataType As Byte [Byte] Int16 Int32 Int64 [Single] [Double] [Decimal] [String] [Char] [Boolean] End Enum


Reply With Quote