Welcome, Guest

Serialize & deserialize class to file

Views: 346 | Like0 | Comments: 0
Serializing can be used to directly write the data properties of the Tutorial class to a file. Deserialization is used to read the data from the file and construct the Tutorial object again.

This sample show serialize and deserialize by use binary format.

1. Import this 2 names space

Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO

2. The class or object that you want implement must insert attribute Serializable.

<system.serializable() >Public Class Person
Private m_sFirstName As String
Private m_sLastName As String

Public Sub New()
End Sub

Public Property FirstName() As String
Return Me.m_sFirstName
End Get
Set(ByVal value As String)
Me.m_sFirstName = value
End Set
End Property

Public Property LastName() As String
Return Me.m_sLastName
End Get
Set(ByVal value As String)
Me.m_sLastName = value
End Set
End Property

Public ReadOnly Property FullName() As String
Return Me.m_sFirstName & "" "" & Me.m_sLastName
End Get
End Property

End Class

3. Sample code show how to do this.

' Create object instance
Dim pPerson As New Person()

pPerson.FirstName = ""TOM""
pPerson.LastName = ""BROWN""

' Create file by FileStream class
Dim fs As FileStream = New FileStream(""c:\test.bin"", FileMode.OpenOrCreate)

' Creat binary object
Dim bf As New BinaryFormatter()

' Serialize object to file
bf.Serialize(fs, pPerson)

' Open file and deserialize to object again
Dim fsRead As New FileStream(""C:\test.bin"", FileMode.Open)
Dim objTest As Object = bf.Deserialize(fsRead)

You describe it, I build it

Great software is not cheap to make.
Quick Services
• Convert HTML to PDF