This example shows serialization and deserialization using a binary formatter.
I have commented the example if you have any problem in understanding th code then please let me know.
Thanks
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'creating a object of rectangle type
Dim R1 As New Rectangle
'initializing the object X Parameter
R1.X = 1
'initializing the object Y Parameter
R1.Y = 1
'initializing the object width Parameter
R1.Width = 10
'initializing the object height Parameter
R1.Height = 20
'creating second object of rectangle type
Dim R2 As New Rectangle
'initializing the object X Parameter
R2.X = 10
'initializing the object Y Parameter
R2.Y = 10
'initializing the object width Parameter
R2.Width = 100
'initializing the object height Parameter
R2.Height = 200
'creating and initializing the object as arraylist
Dim shapes As New ArrayList
'add rectangle 1 object to arraylist item
shapes.Add(R1)
'add rectangle 2 object to arraylist item
shapes.Add(R2)
'add color red object to arraylist item
shapes.Add(Color.Red)
'add color blue object to arraylist item
shapes.Add(Color.Blue)
'create a filestream
Dim savefile As FileStream
'create a new file and return the reference
savefile = File.OpenWrite(Directory.GetCurrentDirectory & "\ShapesColors.bin")
'read the file from beginneing to end
savefile.Seek(0, SeekOrigin.End)
'creating the formatter (Binary formatter)
Dim formatter As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
'new formatter (binary formatter)
formatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
'serialize the arraylist to save file
formatter.Serialize(savefile, shapes)
'close the stream
savefile.Close()
MsgBox("Arraylist serialized successfully")
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'creating filestream to read file
Dim readfile As FileStream
'Open Binary file for reading
readfile = File.OpenRead(Directory.GetCurrentDirectory & "\ShapesColors.bin")
'create SOAP Formatter
Dim BFormatter As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
'Initialize the Binary Formatter
BFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
'create the arraylist object
Dim shapes As ArrayList
'create a rectangle object
Dim R1 As Rectangle
'typecast the object read from SOAP Formatter to arraylist
shapes = CType(BFormatter.Deserialize(readfile), ArrayList)
'declare integer i
Dim i As Integer
For i = 0 To shapes.Count - 1
'loading data to textbox
TextBox1.AppendText(shapes(i).ToString & vbCrLf)
Next
End Sub