尝试将一组结构保存到文件并从文件加载(序列化,反序列化)

时间:2017-03-08 02:06:28

标签: arrays vb.net serialization structure record

这是我的阵列:

    Public RacersArray(AmountOfRacers - 1) As Racer

<Serializable()> Public Structure Racer
    Public Name As String
    Public CleatSize As String
    Public SkillLevel As String
    Public Height As String
    Public Team As String
    Public CompatibilityArr() As String
End Structure

<Serializable()> Public Structure Compatibility
    Public Name As String
    Public Score As Integer
End Structure

以下是我用来尝试保存并从文件加载的代码。该文件正在填充看起来像正确的乱码,但加载数组时,它的索引仍然“没有”

    Public Sub RacersInputSAVE()
    Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
    Dim fStream As New FileStream(SaveLocation, FileMode.Create)

    bf.Serialize(fStream, InputRacers.RacersArray) ' write to file

    fStream.Close()
End Sub

Public Sub RacersInputLOAD()
    Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
    Dim fStream As New FileStream(LoadLocation, FileMode.Open)

    InputRacers.RacersArray = bf.Deserialize(fStream) ' read from file

    fStream.Close()
End Sub

2 个答案:

答案 0 :(得分:1)

出于某种原因,我从来没有好运使用BinaryFormatter序列化到文件。确切的原因是迷失了时间的迷雾,但我知道SoapFormatter对我来说是正确的:

    Using oStream As Stream = File.Open(SaveLocation, FileMode.Create, IO.FileAccess.Write)
        If oStream IsNot Nothing Then
            Call (New System.Runtime.Serialization.Formatters.Soap.SoapFormatter).Serialize(oStream, InputRacers.RacersArray)
        End If
    End Using

答案 1 :(得分:1)

首先可能出错的是:

Public CompatibilityArr() As String

基于名称似乎应该是第二个Compatibility结构。如果是这样,那应该是:

Public CompatibilityArr As Compatibility()

不清楚这是否是所描述问题的一部分(but when loading the array and it's indexes are still 'nothing'是模糊的,因为有多个数组)。否则,第二个结构没有被使用。

下一步,设置Option Strict On。反序列化时,BinaryFormatter始终返回Object,需要将其转换为正确的类型:

Racers = DirectCast(bf.Deserialize(fs), Racer()) ' read from file

通过这2次更改,所有数据使得往返很好。

第三, Structure不是正确的类型。这些应该是类,而不是公共字段/成员,特别是如果涉及任何数据绑定,则使用Properties:

<Serializable()> 
Public Class Racer
    Public Property Name As String
    ...

此外,任何实现Dispose()方法的内容(例如FileStream)都应该在Using块中使用,该块将关闭并处理目标对象:

Dim bf As New BinaryFormatter
Using fs As New FileStream(fileName, FileMode.Create)
    bf.Serialize(fs, Racers) ' write to file
End Using

最后,您可能会发现某些.NET集合(例如List(Of Racer))比数组更容易使用。学习它们的工作方式大约需要15分钟。

MSDN: Choosing Between Class and Struct