【问题标题】:vb.net: reading binary into a projectvb.net:将二进制文件读入项目
【发布时间】:2015-11-09 21:13:42
【问题描述】:

我试图在 .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 时重新加载这个文件。

【问题讨论】:

  • look at this 效果好不好取决于classProject上的内容
  • 谢谢。回读文件时,需要提供文件路径吗?
  • 顺便说一句,您不只是保存二进制文件,而是序列化一个对象(这就是该类很重要的原因)。是的,您需要提供完整路径(“回读”== 反序列化),这不是创建路径的最佳方式(使用 Path.Combine)
  • 再次感谢您。我不知道 Path.Combine
  • 如果您有多个项目,您可以将它们存储在 List 中并一次将它们全部序列化(而不是每个文件一个)as shown here 它使用 Collection 而不是列表,但概念是相同的。如果链接有帮助,请点赞

标签: vb.net binary filestream


【解决方案1】:

您可以使用我的通用序列化 sn-p 从 Xml 或二进制序列化和反序列化。

一个示例用法如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 2011-05-14
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多