Binary Serialization of a Class in a File


It is often required to save details, such as a file history or recently opened files for an application, especially when you are not using a database. Serializing these details in a binary or XML file can be a solution to this problem.

In this article we will be observing binary serialization and deserialization of a class, by implementing Iserializable interface which provides a GetObjectData() method to let user serialize easily using an inbuilt collection. The example we are using here is of a connection string class where we are serializing this class's properties in a file and when the next time the user visits this form, these details are read back again using deserialization.

serialize.jpg


The class which needs to be serialized

This class has all its properties in textboxes and this data will be serialized.

<Serializable()> _
Public Class ConnectionStrings
Implements Runtime.Serialization.ISerializable

Properties to serialize -

Public
textA As String
Public
textB As String
Public
textC As String
Public
Password As String
Public
textD As String

A default constructor is needed to create objects of this class -

Public
Sub New(ByVal database As String, ByVal provider As String, ByVal type As String, ByVal password As String, ByVal extrainfo As String)
textA = database
textB = type
textC = provider
Password = password
textD = extrainfo
End Sub

This constructor is needed to deserialize an object of this class-

Public
Sub New(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext)
textA =
CStr(info.GetValue("dataSource", GetType(String)))
textB =
CStr(info.GetValue("databaseType", GetType(String)))
textC =
CStr(info.GetValue("connectionStringProvider", GetType(String)))
Password =
CStr(info.GetValue("connectionStringDatabasePassword", GetType(String)))
textD =
CStr(info.GetValue("connectionStringExtraInfo", GetType(String)))
End Sub

Binary formatter is used to serialize the class object to a file. The file need not have any specific extension and will be in binary form anyway.

Public
Sub Serialize(ByVal Filename As String, ByVal obj As ConnectionStrings)
Dim s As IO.Stream
Try
s = File.Open(Filename, FileMode.Create, FileAccess.ReadWrite)
Dim b As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
b.Serialize(s, obj) 
' this is where serialization will happen
Finally
s.Close()
End Try
End Sub

Public Shared Function Deserialize(ByVal Filename As String) As ConnectionStrings
Dim s As Stream
Try
s = File.Open(Filename, FileMode.Open, FileAccess.Read)
Dim b As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
Return CType(b.Deserialize(s), ConnectionStrings) ' deserialize and convert the object to connectionStrings type
Finally
s.Close()
End Try
End Function
 
GetObjectData method you will have to implement when you will implment serializable interface -

Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
info.AddValue(
"dataSource", textA)
info.AddValue(
"databaseType", textB)
info.AddValue(
"connectionStringProvider", textC)
info.AddValue(
"connectionStringDatabasePassword", Password)
info.AddValue(
"connectionStringExtraInfo", textD)
End Sub

Public
Function GetAccessConnectionString()
Return textA & textB & textC & Password & textD
End Function

End
Class

Now we will write the code to actually serialize and deserialize the above class. The following code can be written in another class which actually serializes the above class. For serializing we will be making an object of the above class and populate some values in this object. For deserializing we will cast the deserialized object type to that class which it belongs to i.e. connectionStrings class here.

Serializing ConnectionStrings class into a file -

Private
Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim connStrings As SerializationObjects.ConnectionStrings
connStrings =
New SerializationObjects.ConnectionStrings(textD.Text, textA.Text, textB.Text, password.Text, textC.Text)
connStrings.Serialize(
"c:\testsave.ig", connStrings)
DatabaseLocation = textD.Text
DatabasePassword = password.Text
Me.Close()
End Sub

Deserializaing a file to ConnectionStrings class object -

Private
Sub DatabaseConnection_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connStrings As SerializationObjects.ConnectionStrings  ' connections strings is a custom class
connStrings = SerializationObjects.ConnectionStrings.Deserialize("c:\testsave.ig")
If connStrings IsNot Nothing Then
textA.Text = connStrings.textA
textB.Text = connStrings.textB
textC.Text = connStrings.textC
textD.Text = connStrings.textD
password.Text = connStrings.Password
End If
End Sub