clsserializabledata.vb

来自「VB开发的股票软件」· VB 代码 · 共 62 行

VB
62
字号
Imports System.IO
Imports System.Xml.Serialization

Public Class SerializableData

    'make a temporary filename...
    Public Sub Save(ByVal filename As String)
        'make a temporary filename...
        Dim tempFilename As String
        tempFilename = filename & ".tmp"
        'does the file exist?
        Dim tempFileInfo As New FileInfo(tempFilename)
        If tempFileInfo.Exists = True Then tempFileInfo.Delete()
        'open the file...
        Dim stream As New FileStream(tempFilename, FileMode.Create)
        'save the object...
        Save(stream)
        'close the file...
        stream.Close()
        'remove the existing data file and rename the temp file...
        tempFileInfo.CopyTo(filename, True)
        tempFileInfo.Delete()
    End Sub

    'save-actuall perform the serialization...
    Public Sub Save(ByVal stream As Stream)
        'creae a serializer...
        Dim serializer As New XmlSerializer(Me.GetType)
        'save the file...
        serializer.Serialize(stream, Me)
    End Sub

    'load-deserialize from disk...
    Public Shared Function load(ByVal filename As String, ByVal newType As Type) As Object
        'does the file exist?
        Dim fileInfo As New FileInfo(filename)
        If fileInfo.Exists = False Then
            'create a blank version of the object and return that...
            Return System.Activator.CreateInstance(newType)
        End If

        'open the file...
        Dim stream As New FileStream(filename, FileMode.Open)
        'load the object from the stream...
        Dim newObject As Object = load(stream, newType)
        'close the stream...
        stream.Close()
        'returm the object...
        Return newObject
    End Function

    Public Shared Function Load(ByVal stream As Stream, ByVal newType As Type) As Object
        'create a serializer and load the object...
        Dim serializer As New XmlSerializer(newType)
        Dim newObject As Object = serializer.Deserialize(stream)
        'tetrun the new object...
        Return newObject
    End Function

End Class

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?