vb.net:将二进制读入项目

时间:2015-11-09 21:13:42

标签: vb.net binary filestream

我试图在.exe关闭时将项目的属性保存到文件中,并在.exe再次打开时重新加载它们。我尝试保存为.xml但是抛出了异常,所以我试图保存为二进制文件,如下所示:

Dim savedProject As New classProject
savedProject = project

Dim fileName As String
fileName = project.name

Using fs As New System.IO.FileStream(project.directory & "\" & project.name & ".bin", IO.FileMode.OpenOrCreate, FileAccess.Write)
    Dim bf As New BinaryFormatter
    bf.Serialize(fs, savedProject)
End Using

在这个论坛的帮助下,我现在已经看到了很多关于如何以这种方式保存到文件的例子,但是我很难找到重新加载.exe时如何重新加载这个文件。

1 个答案:

答案 0 :(得分:0)

您可以使用我的通用用法序列化片段从Xml或Binary序列化和反序列化。

一个示例用法是:

Dim obj As String() = {"Hello World!"}
SerializationUtil.Serialize(obj, "C:\File.bin", SerializationFormat.Binary)

obj = SerializationUtil.Deserialize(Of String())("C:\File.bin", SerializationFormat.Binary)

源代码:

' ***********************************************************************
' Author   : Elektro
' Modified : 10-November-2015
' ***********************************************************************

#Region " Public Members Summary "

#Region " Methods "

' SerializationUtil.Serialize(Of T)(T, String, SerializationFormat)
' SerializationUtil.Deserialize(Of T)(T, String, SerializationFormat)

#End Region

#Region " Functions "

' SerializationUtil.Deserialize(Of T)(String, SerializationFormat) As T
' SerializationUtil.IsObjectSerializable(Of T)(T, SerializationFormat) As Boolean
' SerializationUtil.IsTypeSerializable(Of T)() As Boolean
' SerializationUtil.IsTypeSerializable(Of T)(T) As Boolean

#End Region

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System
Imports System.Data
Imports System.Diagnostics
Imports System.IO
Imports System.Linq
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Xml.Serialization

#End Region

#Region " Serialization Util "

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Contains serialization related utilities.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example for Binary serialization/deserialization.
''' <code>
''' Dim obj As String() = {"item1", "item2", "item3"}
''' SerializationUtil.Serialize(obj, "C:\File.bin", SerializationFormat.Binary)
''' 
''' obj = SerializationUtil.Deserialize(Of String())("C:\File.bin", SerializationFormat.Binary)
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example for Xml serialization/deserialization.
''' <code>
''' Dim obj As String() = {"item1", "item2", "item3"}
''' SerializationUtil.Serialize(obj, "C:\File.xml", SerializationFormat.Xml)
''' 
''' obj = SerializationUtil.Deserialize(Of String())("C:\File.xml", SerializationFormat.Xml)
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
Public Module SerializationUtil

#Region " Public Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Serializes the data of an Object to the specified file, using the specified serialization format.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="obj">
    ''' The object to be serialized.
    ''' </param>
    ''' 
    ''' <param name="filepath">
    ''' The filepath where to save the serialized data.
    ''' </param>
    ''' 
    ''' <param name="format">
    ''' The serialization format.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Serialize(Of T)(ByVal obj As T,
                               ByVal filepath As String,
                               ByVal format As SerializationFormat)

        Dim serializer As Object = SerializationUtil.GetSerializer(obj, format)

        Using fs As New FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)

            Select Case serializer.GetType

                Case GetType(BinaryFormatter)
                    DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)

                Case GetType(XmlSerializer)
                    DirectCast(serializer, XmlSerializer).Serialize(fs, obj)

            End Select

        End Using

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Deserializes the data of an Object from the specified file, using the specified serialization format.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="filepath">
    ''' The filepath where from deserialize the serialized data.
    ''' </param>
    ''' 
    ''' <param name="format">
    ''' The serialization format.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Function Deserialize(Of T)(ByVal filepath As String,
                                      ByVal format As SerializationFormat) As T

        Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)

        Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)

            Select Case serializer.GetType

                Case GetType(BinaryFormatter)
                    Return DirectCast(DirectCast(serializer, BinaryFormatter).Deserialize(fs), T)

                Case GetType(XmlSerializer)
                    Return DirectCast(DirectCast(serializer, XmlSerializer).Deserialize(fs), T)

            End Select

        End Using

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Deserializes the data of an Object from the specified file, using the specified serialization format.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="filepath">
    ''' The filepath where from deserialize the serialized data.
    ''' </param>
    ''' 
    ''' <param name="format">
    ''' The serialization format.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Deserialize(Of T)(ByRef refObj As T,
                                 ByVal filepath As String,
                                 ByVal format As SerializationFormat)

        refObj = SerializationUtil.Deserialize(Of T)(filepath, format)

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determines whether the specified <see cref="Type"/> can be serialized.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' The <see cref="Type"/> to check.
    ''' </typeparam>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if the specified <see cref="Type"/> can be serialized; otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Function IsTypeSerializable(Of T)() As Boolean

        Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determines whether the specified <see cref="Type"/> can be serialized.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="type">
    ''' The <see cref="Type"/> to check.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if the specified <see cref="Type"/> can be serialized; otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Function IsTypeSerializable(Of T)(ByVal type As T) As Boolean

        Return SerializationUtil.IsTypeSerializable(Of T)()

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determines whether the specified object can be serialized.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="obj">
    ''' The object to check.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if the specified object can be serialized; otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Function IsObjectSerializable(Of T)(ByVal obj As T,
                                               ByVal format As SerializationFormat) As Boolean

        Dim serializer As Object = SerializationUtil.GetSerializer(obj, format)

        Using ms As New MemoryStream

            Try
                Select Case serializer.GetType

                    Case GetType(BinaryFormatter)
                        DirectCast(serializer, BinaryFormatter).Serialize(ms, obj)

                    Case GetType(XmlSerializer)
                        DirectCast(serializer, XmlSerializer).Serialize(ms, obj)

                End Select

                Return True

            Catch ex As InvalidOperationException
                Return False

            Catch ex As Exception
                Throw

            End Try

        End Using

    End Function

#End Region

#Region " Private Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the proper data serializer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="format">
    ''' The serialization format.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentException">
    ''' Bad Serialization Format.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Private Function GetSerializer(Of T)(ByVal format As SerializationFormat) As Object

        Select Case format

            Case SerializationFormat.Binary
                Return New BinaryFormatter

            Case SerializationFormat.Xml
                Return New XmlSerializer(type:=GetType(T))

            Case Else
                Throw New ArgumentException(message:="Bad Serialization Format.", paramName:="format")

        End Select

    End Function

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the proper data serializer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <typeparam name="T">
    ''' </typeparam>
    ''' 
    ''' <param name="obj">
    ''' The object to check.
    ''' </param>
    ''' 
    ''' <param name="format">
    ''' The serialization format.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="System.ArgumentException">
    ''' Bad Serialization Format.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Private Function GetSerializer(Of T)(ByVal obj As T,
                                         ByVal format As SerializationFormat) As Object

        Select Case format

            Case SerializationFormat.Binary
                Return New BinaryFormatter

            Case SerializationFormat.Xml
                Return New XmlSerializer(obj.GetType)

            Case Else
                Throw New ArgumentException(message:="Bad Serialization Format.", paramName:="format")

        End Select

    End Function

#End Region

End Module

#End Region