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()

5 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
  3. Awesome just what I needed. Thanks

    I have create an list(of PCs) and saved in a file as you explained in this tuto but when I try to read it and stoked in an object it doesn't work!!

    Public PCsList As New List(Of PCs)
    .
    .
    .
    If FileIO.FileSystem.FileExists(FileSrc) Then
    Dim fsRead As New FileStream(FileSrc, FileMode.Create)
    PCsList = bf.Deserialize(fsRead)
    fsRead.Close()
    RefreshList()
    End If

    ReplyDelete
    Replies
    1. sorry i have made a mistake filemode.open

      If FileIO.FileSystem.FileExists(FileSrc) Then
      Dim fsRead As New FileStream(FileSrc, FileMode.open)
      PCsList = bf.Deserialize(fsRead) ' Position of the error <<<<<<<<<<<<<<<<
      fsRead.Close()
      RefreshList()
      End If

      note: System.NullReferenceException: La référence d'objet n'est pas définie à une instance d'un objet.

      Delete

Thanks for your comment.