2007-12-13

Serialize & Deserialize Class To File

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
Get
Return Me.m_sFirstName
End Get
Set(ByVal value As String)
Me.m_sFirstName = value
End Set
End Property

Public Property LastName() As String
Get
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
Get
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)
fs.Close()

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

3 comments:

  1. Awesome just what I needed.

    ReplyDelete
  2. Really great example!!! This is the kind of examples that I think is usefulness: simple and functional.
    Thanks.

    (Now, I just have to find out how to put more than one object into binary file... jeje)

    ReplyDelete
    Replies
    1. Put all Objects in a Hashtable and then dump it

      Delete

Thanks for your comment.