【VB.NET】序列化

摘要:【VB.NET】序列化

好文

Huan-Lin 學習筆記 on DotBlogs - .NET 筆記:序列化

余小章 @ 大內殿堂 - 物件序列化 Serialization

.NET 隨筆 - 序列化 (Serialization)

 

觀念

  • 二進位 格式序列化及反序列化
  • SOAP 格式序列化及反序列化
  • XML  格式序列化及反序列化

 

程式碼

 

Imports System.IO
Imports System.Runtime.Serialization '自訂的時候加入
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Xml.Serialization

Public Class Form1

    '寫二進位序列化物件
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        '1 開啟檔案
        Dim fs As FileStream = New FileStream("Serial.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '2 初始二進位序列化
        Dim bf As BinaryFormatter = New BinaryFormatter()
        '3 設定要轉二進位的資料
        Dim BinaryStr As String = "YOYO是一隻可愛的柯基"
        '4 用Serialize 方法將序列化指定的檔案
        bf.Serialize(fs, BinaryStr)
        '釋放
        fs.Dispose()

    End Sub

    '讀二進位序列化物件
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        '1 開啟檔案
        Dim myReader As FileStream = New FileStream("Serial.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '2 初始二進位序列化
        Dim BfRead As BinaryFormatter = New BinaryFormatter()
        '3 將序列化資料還原
        Dim BinaryStr As String = BfRead.Deserialize(myReader)
        '4 輸出
        MessageBox.Show(BinaryStr)
        '5 釋放資料
        myReader.Dispose()

    End Sub

    '寫SOAP序列化物件
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        '1 要先到 "加入參考/.net/選擇 System.Runtime.Serialization.Formatters.Soap 加入參考"
        '2 引用串流開啟檔案
        Dim myFS As FileStream = New FileStream("DataFile.XML", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '3 初始化SOAP序列化
        Dim mySF As SoapFormatter = New SoapFormatter()
        '4 建立hashtable類別資料
        Dim myData As Hashtable = New Hashtable()
        myData.Add("1", "YOYO,柯基,母,3歲,腳不好")
        myData.Add("2", "阿布,柯基,公,5歲,很會頂")
        myData.Add("3", "Bank,黃金,公,5歲,動物治療師")
        '5 用Serialize 方法將序列化指定到檔案
        mySF.Serialize(myFS, myData)
        '6 釋放
        myFS.Dispose()

    End Sub

    '讀SOAP 序列化物件
    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        '1 建立串流開啟檔案
        Dim myFS As FileStream = New FileStream("DataFile.XML", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '2 初始化SOAP 序列化
        Dim mySoapFR As SoapFormatter = New SoapFormatter()
        '3 讀取資料然後還原序列化
        Dim myData As Hashtable = mySoapFR.Deserialize(myFS)
        '4 輸出
        For Each obj As DictionaryEntry In myData
            MessageBox.Show(obj.Key & ". " & obj.Value)
        Next

    End Sub

    '寫XML序列化物件
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

        '1 引用dll
        '2 建立串流開啟檔案
        Dim myFS As FileStream = New FileStream("XMLSerializeData.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '3 建立資料
        Dim MyStr As String = "科基好胖好可愛"
        '4 序列化初始化
        Dim myXS As XmlSerializer = New XmlSerializer(GetType(String))
        '5 序列化資料寫入
        myXS.Serialize(myFS, MyStr)
        '釋放
        myFS.Dispose()

    End Sub

    '讀XML序列化物件
    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click

        '建立串流開啟檔案
        Dim myFS As FileStream = New FileStream("XMLSerializeData.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '初始序列化
        Dim myXS As XmlSerializer = New XmlSerializer(GetType(String))
        '將資料還原
        Dim myData As String = myXS.Deserialize(myFS)
        '顯示資料
        MessageBox.Show(myData)
        '釋放
        myFS.Dispose()

    End Sub

    'Class 和XML序列化
    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click

        '1 先建立下面的Class : clsProduct ↓↓↓↓↓↓
        '2 宣告 class
        Dim p As New clsProduct
        p.Name = "皇家飼料"
        p.Desc = "出過問題"
        p.Qty = 500

        '3 將clsProduct此class XML序列化
        Dim objStreamWriter As New StreamWriter("C: \Product.xml")
        Dim x As New XmlSerializer(p.GetType)
        x.Serialize(objStreamWriter, p)
        objStreamWriter.Dispose()

    End Sub

    'Class : clsProduct
    Public Class clsProduct

        Private _Name As String
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value
            End Set
        End Property

        Private _Desc As String
        Public Property Desc() As String
            Get
                Return _Desc
            End Get
            Set(ByVal value As String)
                _Desc = value
            End Set
        End Property

        Private _Qty As Integer
        Public Property Qty() As Integer
            Get
                Return _Qty
            End Get
            Set(ByVal value As Integer)
                _Qty = value
            End Set
        End Property

    End Class

    '讀取class 建立的xml檔
    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click

        Dim xmlStream As FileStream = New FileStream("C:\Product.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        Dim p As clsProduct = New clsProduct()
        Dim x As New XmlSerializer(p.GetType())
        p = x.Deserialize(xmlStream)
        xmlStream.Dispose()
        MessageBox.Show(p.Name & Environment.NewLine() & _
                                            p.Desc & Environment.NewLine() & _
                                            p.Qty & Environment.NewLine())

    End Sub

    '建立自訂序列化行為
    Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click

        '1 建立Serializable的class↓↓↓↓↓↓
        '2 class 物件化
        Dim myClsIS As ClsISerialization = New ClsISerialization()
        '3 建立串流寫入檔案
        Dim Fs As FileStream = New FileStream("C:\ttt.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        '4 建立BinaryFormatter 物件
        Dim bf As BinaryFormatter = New BinaryFormatter()
        '5序列化
        bf.Serialize(Fs, myClsIS)
        myClsIS = Nothing
        Fs.Dispose()

        ''讀取建立的資料
        'Fs = New FileStream("C:\ttt.bin", FileMode.Open, FileAccess.Read)
        'bf = New BinaryFormatter()
        'myClsIS = New ClsISerialization()
        'bf.Deserialize(Fs)
        'Fs.Close()
        'Fs.Dispose()

    End Sub

    'Serializable 的class
     _
    Public Class ClsISerialization
        Implements ISerializable

        Public intNumber As Integer = 100
        Public message As String = "This is a test string 123!!"
        Public ingTest As Long
        Public intArrayX(10) As Integer
        Public intArrayY(10) As Integer

        '建立sub,名為 : ChangeMmberValue
        Sub ChangeMmberValue()
            For i As Integer = 0 To 9
                intArrayX(i) = i * 100
            Next
            intNumber = 2000
            message = "This is update String!!"
        End Sub

        '實做此方法,此方法會在類別實體化後,自動被呼叫
        Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
            info.AddValue("intNumber", intNumber)
            info.AddValue("message", message)
            info.AddValue("intArrayX", intArrayX)
        End Sub

        'New 一個ClsSerialization class 和一個建構式
        Public Sub ClsSerialization()
            ChangeMmberValue()
        End Sub

        '建構式,用於還原序列化物件
        Public Sub ClsISerialization(ByVal info As SerializationInfo, ByVal context As StreamingContext)
            intNumber = CInt(info.GetValue("intNumber", GetType(Integer)))
            message = CStr(info.GetValue("message", GetType(String)))
            intArrayX = DirectCast(info.GetValue("intArrayX", GetType(Integer())), Integer())
        End Sub

    End Class

    '修正無法序列化的資料
    Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button12.Click

    End Sub
   

End Class

 

檔案下載 Serialization.rar

 

 

既然走了! 就勇往的去 ......