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

时间:2011-05-31 11:27:41

标签: 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

使用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

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

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

2 个答案:

答案 0 :(得分:5)

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

<Serializable()> Public Structure Two

...

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

答案 1 :(得分:2)

我认为保存结构数组的更好方法是使用序列化。您可以使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatterSystem.Xml.Serialization.XmlSerializerSystem.Runtime.Serialization.Formatters.Soap.SoapFormatter来序列化数组。