vb.net:将二进制文件读入项目
我试图在.exe关闭时将项目属性保存到文件中,并在.exe再次打开时重新加载它们。我尝试保存为.xml,但引发了异常,因此我尝试保存为二进制文件,如下所示:vb.net:将二进制文件读入项目,vb.net,binary,filestream,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 & "
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时重新加载这个文件 您可以使用我的通用用法序列化片段从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
您可以使用我的泛型用法序列化片段从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
它是否运行良好取决于
classProject
谢谢。当读回文件时,我需要提供文件路径吗?顺便说一句,你不仅仅是在保存二进制文件,而是在序列化一个对象(这就是为什么这个类很重要)。是的,您需要提供完整的路径(“读回”==反序列化),这不是创建路径的最佳方式(使用路径。组合)再次感谢您。我不知道Path.combinei如果你有几个项目,你可以将它们存储在一个列表中,然后一次将它们序列化(而不是每个文件一个)。它使用集合而不是列表,但概念是一样的。如果这些链接有帮助,请根据classProject
Thank you上的内容向他们投票,看它是否工作正常。当读回文件时,我需要提供文件路径吗?顺便说一句,你不仅仅是在保存二进制文件,而是在序列化一个对象(这就是为什么这个类很重要)。是的,您需要提供完整的路径(“读回”==反序列化),这不是创建路径的最佳方式(使用路径。组合)再次感谢您。我不知道Path.combinei如果你有几个项目,你可以将它们存储在一个列表中,然后一次将它们序列化(而不是每个文件一个)。它使用集合而不是列表,但概念是一样的。如果链接有帮助,请向上投票