'the example class
'make sure the class has the serializable attribute
<Serializable()> _
Public Class Tester
Private _Name As String = String.Empty
Private _Other As Integer = 0
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal Value As String)
_Name = Value
End Set
End Property
Public Property Other() As Integer
Get
Return _Other
End Get
Set(ByVal Value As Integer)
_Other = Value
End Set
End Property
Public Sub New()
'xml serialization has trouble if there is no default constructor
End Sub
Public Sub New(ByVal name As String, ByVal other As Integer)
_Name = name
_Other = other
End Sub
End Class
'the code to test it
Dim test As New Tester("Test1", 6)
'delete old file if found
If IO.File.Exists("data.dat") Then IO.File.Delete("data.dat")
'make the file and stream
Dim fs As New IO.FileStream("data.dat", IO.FileMode.CreateNew)
'serialize it to binary data
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(fs, test)
fs.Close()
'open file again
fs = New IO.FileStream("data.dat", IO.FileMode.Open)
'now deserialize and display data to make sure it worked
Dim retTest As Tester = bf.Deserialize(fs)
fs.Close()
MsgBox(String.Concat("Name:", retTest.Name, " Other:", retTest.Other), , "Binary")
'now here is the samething but to xml
'delete old file if found
If IO.File.Exists("data.xml") Then IO.File.Delete("data.xml")
'make the file and stream
fs = New IO.FileStream("data.xml", IO.FileMode.CreateNew)
'serialize it to xml data
Dim xf As New Xml.Serialization.XmlSerializer(GetType(Tester))
xf.Serialize(fs, retTest)
fs.Close()
'open file again
fs = New IO.FileStream("data.xml", IO.FileMode.Open)
'now deserialize and display data to make sure it worked
Dim xmlTest As Tester = xf.Deserialize(fs)
fs.Close()
MsgBox(String.Concat("Name:", xmlTest.Name, " Other:", xmlTest.Other), , "XML")