在VB.NET中保存结构数组的最佳方法是什么?

Ske*_*a87 1 vb.net arrays file-io structure

我有2个结构

Public Structure One                    
        Public ItemOne As String
        Public ItemTwo As Integer
    End Structure

    Public Structure Two                   
        Public ItemOne As String
        Public ItemTwo As Integer
        Public ItemThree As Integer
        Public ItemFour As Integer
        Public ItemFive As Integer
    End Structure

Public TestOne(0) as One
Public TestTwo(19) as Two
Run Code Online (Sandbox Code Playgroud)

使用FileOpen,FilePut和FileClose方法,我收到一个错误:(作为示例,仅限于相关代码)

    Public Sub WriteOne()
                FileOpen(1, "One.dat", OpenMode.Random, OpenAccess.Write)
                FilePut(1, TestOne)
                FileClose(1)
    End Sub

    Public Sub ReadOne()
                FileOpen(1, "One.dat", OpenMode.Random, OpenAccess.Read)
                FileGet(1, TestOne)
                FileClose(1)
    End Sub

    Public Sub WriteTwo()
                FileOpen(1, "Two.dat", OpenMode.Random, OpenAccess.Write)
                FilePut(1, TestTwo)
                FileClose(1)
    End Sub

    Public Sub ReadTwo()
                FileOpen(1, "Two.dat", OpenMode.Random, OpenAccess.Read)
                FileGet(1, TestTwo)
                FileClose(1)
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ReadOne()
        ReadTwo()
        Label1.Text = Cstr(TestOne(0).ItemTwo)
        Label2.Text = Cstr(TestTwo(4).ItemFour)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TestOne(0).ItemTwo = 9
        TestTwo(4).ItemFour = 78
        WriteOne()
        WriteTwo()
    End Sub
Run Code Online (Sandbox Code Playgroud)

结果在未处理的异常中.记录长度不佳.然后,如果我关闭它并重新打开它,我会得到一个"无法读取超出流末尾"的错误.

那么保存结构数组的最佳方法是什么?二进制读/写器?为什么这种方式不起作用(即使它来自VB6)

xpd*_*pda 5

您可以使用序列化BinaryFormatter并使用Serialize将其保存到文件流,然后使用Deserialize读取它.您需要添加<Serializable()>到结构声明中.

<Serializable()> Public Structure Two
Run Code Online (Sandbox Code Playgroud)

...

Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim fStream As New FileStream(filename, FileMode.OpenOrCreate)

bf.Serialize(fStream, TestTwo) ' write to file
fStream.Position = 0 ' reset stream pointer
TestTwo = bf.Deserialize(fStream) ' read from file
Run Code Online (Sandbox Code Playgroud)