我想学习如何使用Visual Basic Studio Express 2013 for Windows Desktop从文件中写入和读取数据。
具体来说,我有一个名为Pilots的课程。该课程包括姓氏和姓氏的文本,以及代表等级,技能,任务和状态的整数。
有一个名为Squadron的ArrayList包含18个(开始时)飞行员。
我想要做的是保存然后将Squadron中的所有数据加载到文件中。而且我不确定如何让它正常工作。我读过很多书籍和网站,但是在某个地方,我只是不理解如何让它正常工作。
此时,我已经能够将数据写入文件....但我没有运气将其从文件中取回。
写出来......我正在使用这段代码:
Dim currentpilot As New Pilot("John", "Doe")
' Create the BinaryWriter and use File.Open to create the file.
Using writer As BinaryWriter = New BinaryWriter(File.Open("squadron.dat", FileMode.Create))
' Write each integer.
writer.Write(SquadronList.Count)
For index = 0 To SquadronList.Count - 1
currentpilot = CType(SquadronList(index), Pilot)
writer.Write(currentpilot.pFirstName)
writer.Write(currentpilot.pLastName)
writer.Write(currentpilot.pSkill)
writer.Write(currentpilot.pRank)
writer.Write(currentpilot.pStatus)
writer.Write(currentpilot.pMissions)
writer.Write(currentpilot.pKills)
Next
End Using
writer.Write(SquadronList.Count)
行用于记录文件中实际Pilot记录的数量。我不知道是否有必要。
该文件写入磁盘并只用记事本查看它,它似乎确实有正确的数据。
问题是让它退出。这段代码很快就失败了......
Using reader As BinaryReader = New BinaryReader(File.OpenRead("squadron.dat"))
Dim index As Integer = reader.ReadInt32
For counter = 0 To index - 1
currentpilot.pFirstName = reader.ReadString
currentpilot.pLastName = reader.ReadString
currentpilot.pSkill = reader.ReadInt16
currentpilot.pRank = reader.ReadInt16
currentpilot.pStatus = reader.ReadInt16
currentpilot.pMissions = reader.ReadInt16
currentpilot.pKills = reader.ReadInt16
SquadronList.Add(currentpilot)
Next
End Using
所以......任何建议或指导都将不胜感激!