I have 2 Structures
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开发者_Go百科
Public TestTwo(19) as Two
Using the FileOpen, FilePut and FileClose method, I get an error: (Stripped down to only related code as an example)
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
Results In an Unhandled exception. Bad Record Length. and then If I close it and reopen it I get an 'Unable to read beyond end of stream' error.
So what is the best way to save an array of structures? Binary Reader/Writer? and why does this way not work (Even if its derived from VB6)
You can use the serialization BinaryFormatter and save it to a file stream with Serialize, then read it using Deserialize. You'll need to add <Serializable()>
to your structure declarations.
<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
I think a better way to save an array of structures is to use serialization. You can use System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
, System.Xml.Serialization.XmlSerializer
or System.Runtime.Serialization.Formatters.Soap.SoapFormatter
to serialize the array.
精彩评论