This Article Demonstrates the Process of Serialization and De-Serialization in VB.NET
Serialization in DotNet
Serialization is the Process of objects getting transformed to stream of bytes to be stored in a File, Memory or a Database. The Main Purpose of Serialization is to Save the State of the object in order to recreate it when needed. The reverse of this Process is called as De-Serialization.
Serialization as said before stores the state of the object in Stream of bytes which can be stored in a File, Database or in Memory.
Using which a developer can easily recreate the same instance of the object with all its properties whenever required.
Different Serialization Formats
A. Binary Format: Binary formatter is the most efficient way to serialize objects that will only be read by .NET framework-based applications. This formatter class is in the System.Runtime.Serialization.Formatters.Binary
B. Soap Format : This XML Based formatter is easily read by .NET and non-.NET framework based applications .
A) Working sample of Binary Formatter :
1) You need to write the Serializable Class
<Serializable()> _
Class SerializeObjects
Dim name As String
Public Property EmpName() As String
Get
Return name
End Get
Set(ByVal value As String)
name = value
End Set
End Property
End Class
2) Now The class in which the Serialization will take place
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Class BinaryExample
Shared Sub Main()
Dim ser As New SerializeObjects
ser.EmpName = "Hefin"
Dim binFor As New BinaryFormatter()
binFor.Serialize(File.Create("Demo.bin"), ser)
End Sub
End Class
B) Working sample of the SOAP formatter
The Serializable class remains the same only thing that changes is the class where the serialization will take place.
NOTE : A reference to the Namespace System.Runtime.Serialization.Formatters.Soap needs to be added.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Soap
Class SoapExample
Shared Sub Main()
Dim ser As New SerializeObjects
ser.EmpName = "Hefin"
Dim soapFor As New SoapFormatter()
soapFor.Serialize(File.Create("Demo.xml"), ser)
End Sub
End Class
De-Serialization :- The reverse of the serialization process is called the De-Serialization .
De-Serialization of the SOAP Serialized Object
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Soap
Class SoapExample
Shared Sub Main()
Dim ser As New SerializeObjects
Dim soapFor As New SoapFormatter()
ser = soapFor.Deserialize(File.Open("Demo.xml", FileMode.Open))
Console.WriteLine(ser.EmpName)
End Sub
End Class
De-Serialization of the Binary Serialized Object
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Class BinaryExample
Shared Sub Main()
Dim ser As New SerializeObjects
Dim binFor As New BinaryFormatter()
ser = binFor.Deserialize(File.Open("Demo.xml", FileMode.Open))
Console.WriteLine(ser.EmpName)
End Sub
End Class
Regards
Hefin Dsouza