Introduction
In this article, I want to show you how to write the content of a Visual Basic structure into a binary file. This can be useful since the various methodologies exposed by the .NET Framework (like FileStream
, BinaryWriter
, and My
objects) can write to binary files only data types that belong to the Base Class Library.
So, what is the solution? We can serialize the structure and write the serialized object to a binary file.
Using the code
First of all, open Visual Studio 2008 and create a new Visual Basic 2008 Console Application. We could have a very simple Structure
called Software
, which contains information about a computer program:
Module Module1
<serializable() /> Structure Software
Dim programName As String
Dim productionYear As Integer
Dim programProducer As String
End Structure
Sub MakeBinaryFile()
Dim Program As Software
Program.programProducer = "Microsoft"
Program.programName = "Windows Vista"
Program.productionYear = 2006
The next step is to serialize the structure. We could implement a method to accomplish this. Here, I’ve specified a predetermined file name, but this is not often the real case. Comments inside the following code should be helpful:
Dim BF As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim MS As New System.IO.MemoryStream()
BF.Serialize(MS, Program)
My.Computer.FileSystem.WriteAllBytes("c:\temp\programs.bin", MS.GetBuffer(), False)
Finally, we can read back our binary file to check that everything works correctly. The following code snippet accomplishes this:
Dim bytes As Byte() = My.Computer.FileSystem.ReadAllBytes("c:\temp\programmi.bin")
Program = DirectCast(BF.Deserialize(New System.IO.MemoryStream(bytes)), Software)
Console.WriteLine(Program.programName + " produced by " + _
Program.programProducer + " in the Year " + _
Program.productionYear.ToString)
Console.ReadLine()
End Sub
We just need to call our method from within the Sub Main
, in the following way:
Sub Main()
MakeBinaryFile()
End Sub
Points of interest
For a simple structure like the one above, the code can appear not very useful. But you must think that structures can contain .NET objects of any kind (e.g.: streams).
Moreover, objects serialization offers good levels of performance in reading/writing.