What is Serialization?
serialization is process of converting object into stream
Lets learn how to serialize and restore serialized file
In the following lines I will show how we can serialize a class in binary and soap format.
1. First create a class with the
Public Title As String
Public Number As Int16
End Class
2. create a form and add the following imports and code
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.soap
' this sub would create the instance of the class and add in the arraylist and then finally save the 'object in Serilize.txt file which can be viewed in notepad
Sub SaveSerializedFile()
Dim lst As New ArrayList
Dim obj As New Serilize
obj.Title = "This is First title"
obj.Number = 1
lst.Add(obj)
obj = New Serilize
obj.Title = "This is Second Title"
obj.Number = 2
lst.Add(obj)
obj = New Serilize
obj.Title = "This is third Title"
obj.Number = 3
lst.Add(obj)
Dim s As New FileStream("Serilize.txt", FileMode.Create)
'Dim f As New BinaryFormatter
' If we want to serilize the object using binary formatter then
' we have to disable the soap formatter and enable Binaryformatter
' declarations.
Dim f As New SoapFormatter
f.Serialize(s, lst)
s.Close()
End Sub
Sub RestoreSerializedFile()
Dim s = New FileStream("Serilize.txt", FileMode.Open)
'Dim f As BinaryFormatter = New BinaryFormatter
' If we want to serilize the object using binary formatter then
' we have to disable the soap formatter and enable Binaryformatter
' declarations.
Dim f As SoapFormatter = New SoapFormatter
Dim RestoredList As ArrayList
RestoredList = CType(f.Deserialize(s), ArrayList)
s.close()
Dim x As Serilize
For Each x In RestoredList
txtDisplay.Text = txtDisplay.Text & x.Title & " Lesson Number " & x.Number
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveSerializedFile()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
RestoreSerializedFile()
End Sub
No comments:
Post a Comment