2010年11月15日

序列化物件與檔案儲存

如何將物件寫進去文字檔案,在下次讀取可以取出整個來使用, 這時可考慮序列化物件:


 Public Class Setting
    Public hh1 As String
    Public mm1 As String
    Public hh2 As String
    Public mm2 As String
    Public hh3 As String
    Public mm3 As String
    Public hh4 As String
    Public mm4 As String
    Public hh5 As String
    Public mm5 As String
    Public music1 As String
    Public music2 As String
    Public music3 As String
    Public music4 As String
    Public music5 As String
End Class

   Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim data As musicPlayer.Setting = New musicPlayer.Setting()
        data.hh1 = Me.txb_HH1.Text
        data.hh2 = Me.txb_HH2.Text
        data.hh3 = Me.txb_HH3.Text
        data.hh4 = Me.txb_HH4.Text
        data.hh5 = Me.txb_HH5.Text
        data.mm1 = Me.txb_MM1.Text
        data.mm2 = Me.txb_mm2.Text
        data.mm3 = Me.txb_mm3.Text
        data.mm4 = Me.txb_mm4.Text
        data.mm5 = Me.txb_mm5.Text
        data.music1 = Me.txb_music1.Text
        data.music2 = Me.txb_music2.Text
        data.music3 = Me.txb_music3.Text
        data.music4 = Me.txb_music4.Text
        data.music5 = Me.txb_music5.Text

        Dim fs As FileStream = New FileStream("C:\Setting.Data", FileMode.Create)
        Dim bf As BinaryFormatter = New BinaryFormatter
        bf.Serialize(fs, data)
        fs.Close()

    End Sub
    Sub loadSetting()
        Try
            Dim fs As FileStream = New FileStream("C:\Setting.Data", FileMode.Open)
            Dim bf As BinaryFormatter = New BinaryFormatter
            Dim data As musicPlayer.Setting = New musicPlayer.Setting()
            data = CType(bf.Deserialize(fs), musicPlayer.Setting)
            fs.Close()
            Me.txb_HH1.Text = data.hh1
            Me.txb_HH2.Text = data.hh2
            Me.txb_HH3.Text = data.hh3
            Me.txb_HH4.Text = data.hh4
            Me.txb_HH5.Text = data.hh5
            Me.txb_MM1.Text = data.mm1
            Me.txb_mm2.Text = data.mm2
            Me.txb_mm3.Text = data.mm3
            Me.txb_mm4.Text = data.mm4
            Me.txb_mm5.Text = data.mm5
            Me.txb_music1.Text = data.music1
            Me.txb_music2.Text = data.music2
            Me.txb_music3.Text = data.music3
            Me.txb_music4.Text = data.music4
            Me.txb_music5.Text = data.music5
        Catch ex As Exception

        End Try
    End Sub


1 則留言: