问题描述
|
我有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,OpenAccess.Read)
FileGet(1,TestOne)
FileClose(1)
End Sub
Public Sub WriteTwo()
FileOpen(1,\"Two.dat\",TestTwo)
FileClose(1)
End Sub
Public Sub ReadTwo()
FileOpen(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)
解决方法
您可以使用序列化BinaryFormatter并通过Serialize将其保存到文件流中,然后使用Deserialize读取它。您需要在结构声明中添加“ 2”。
<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
, 我认为保存结构数组的更好方法是使用序列化。您可以使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
,System.Xml.Serialization.XmlSerializer
或System.Runtime.Serialization.Formatters.Soap.SoapFormatter
序列化阵列。