Hi this is a very simple example of how you can save arrays of Structure to files you remember how easy this was in VB6 well it almost the same. This example just shows how to save data using a basic person example.
Ok start a new forms project add two commend buttons
Button1
Name : cmdSave
Text : Save
Button2
Name : cmdLoad
Text : Load
Next add the code, then hit the load button.
This will save a small data example button load will display persons name in message box. Hope you find it useful comments suggestions are welcome.
Code
vbnet Code:
Option Explicit On
Public Class Form1
Private Structure TPerson
Dim Id As Integer
Dim Name As String
Dim Age As Integer
End Structure
Private Persons() As TPerson
Private PersonCount As Integer
Private Sub Reset()
'Reset person count and array
PersonCount = 0
Erase Persons
End Sub
Private Sub AddPerson(ByVal ID As Integer, ByVal Name As String, ByVal Age As Integer)
ReDim Preserve Persons(PersonCount)
'Add person to persons
With Persons(PersonCount)
.Id = ID
.Name = Name
.Age = Age
End With
'INC Counter
PersonCount += 1
End Sub
Private Function LoadFromFile(ByVal Source As String) As Boolean
Dim fp As Integer = FreeFile()
Dim sig(2) As Char
FileOpen(fp, Source, OpenMode.Binary, OpenAccess.Read)
'Get header
FileGet(fp, sig(0))
FileGet(fp, sig(1))
FileGet(fp, sig(2))
If (New String(sig)) <> "BAG" Then
Return False
Else
'Get person count
FileGet(fp, PersonCount)
'Get person records.
ReDim Preserve Persons(PersonCount)
FileGet(fp, Persons)
FileClose(fp)
'Return good value
Return True
End If
End Function
Private Sub WriteToFile(ByVal Source As String)
Dim fp As Integer = FreeFile()
Dim sig(2) As Char
'Setup header
sig(0) = "B"
sig(1) = "A"
sig(2) = "G"
FileOpen(fp, Source, OpenMode.Binary, OpenAccess.Write)
FilePut(fp, sig(0))
FilePut(fp, sig(1))
FilePut(fp, sig(2))
FilePut(fp, Persons.Length - 1)
FilePut(fp, Persons)
FileClose(fp)
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
'Add some random people.
AddPerson(0, "Ben", 35)
AddPerson(1, "Joe", 25)
AddPerson(2, "Gemma", 32)
AddPerson(3, "Bill", 56)
AddPerson(4, "Jack", 24)
'Write to filename.
WriteToFile("C:\out\data\data.txt")
'Reset
Reset()
End Sub
Private Sub cmdLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLoad.Click
'Load persons data.
If LoadFromFile("C:\out\data\data.txt") <> True Then
'Show message message.
MessageBox.Show("Error loading data", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Else
'Show persons
For x As Integer = 0 To PersonCount
MessageBox.Show(Persons(x).Name, "", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Next
'Reset
Reset()
End If
End Sub
End Class