将对象序列化为文件并读回列表

时间:2016-04-11 15:54:46

标签: vb.net serialization

在我的vb.net应用程序中,我将一个对象序列化为一个文件。我不时地这样做。 我关闭我的应用程序 我开始我的应用程序,我尝试/想要读取我写的对象列表,但它不起作用。

这是我的模特:

<Serializable()>
Public Class test
    Public FontColor As Color = Color.Black
    Public Contrast As Int32 = 0
    Public Text As String = ""
End Class

这就是我写入文件的方式:

Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim stream As New FileStream(Application.StartupPath + "\testme.txt", FileMode.Append, FileAccess.Write, FileShare.None)
Dim TextValues As New test
TextValues.Contrast = 10
TextValues.FontColor = Color.AliceBlue
TextValues.Text = "hello andy"

formatter.Serialize(stream, TextValues)
stream.Close()

注意,是的,我知道我应该使用关键字&#39;使用&#39; :)

这是我回读的方式:

Dim formatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim stream As New FileStream(Application.StartupPath + "\testme.txt", FileMode.Open, FileAccess.Read, FileShare.Read)

REM THIS WORKS OK BUT FOR ONLY 1 OBJECT ******************************
Dim TextValues = CType(formatter.Deserialize(stream), test)
REM *********************************************************************

REM ***THIS JUST ERRORS *************************************************
Dim TextValues2 = CType(formatter.Deserialize(stream), List(Of test))
REM *********************************************************************

stream.Close()

1 个答案:

答案 0 :(得分:0)

如果要编写和读取多个List(Of TextValue)对象,可以创建TextValue并序列化/反序列化。