الأربعاء، 7 ديسمبر 2011

Serialize & Deserialize Class To File


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 PersonPrivate m_sFirstName As StringPrivate m_sLastName As String
Public Sub New()
End Sub
Public Property FirstName() As StringGet Return Me.m_sFirstNameEnd GetSet(ByVal value As String) Me.m_sFirstName = valueEnd SetEnd Property
Public Property LastName() As StringGet Return Me.m_sLastNameEnd GetSet(ByVal value As String) Me.m_sLastName = valueEnd SetEnd Property
Public ReadOnly Property FullName() As StringGet Return Me.m_sFirstName & " " & Me.m_sLastNameEnd GetEnd 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()

ليست هناك تعليقات:

إرسال تعليق