Hel with binary files and structures

dennisvb

Member
Joined
Nov 19, 2009
Messages
10
Programming Experience
10+
It's like when they designed VB.Net they said VB6 is too straight foreward and simple let's complicate it as much as possible.

To read a record in a binary file in VB^ I would define a type with all the fields specifying strings as STRING * whatever the length of the field was.

For example:
Type Record
Field1 as string *15
Field2 to as string * 20
Field3 as String * 10
field4 as byte(10)
End Type

Dim filerecord as record

I would the open my binary fiel and do a
Get#1,, filerecord

The record would be read and all the fielsd would be in place.

Now with the new Structure we cant dimension an array in the Structure
And wjhen declaring strings we can't specify the length.

I tried to create structire and use a stream binary reader. and just read afixed number of bytes into the type, The program says it canvert bytes to my fiels.

So how do I do this. Or has Microsoft in their infinite wisdom left no way to do this.
 
Here's an example using fixed length strings and an array in a structure.

VB.NET:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim listOfMyStruct As New List(Of myStruct) From
        {
            New myStruct With {.Field1 = "abcde", .Field2 = 123, .Arr = {"ab", "cd", "ef"}},
            New myStruct With {.Field1 = "fghij", .Field2 = 234, .Arr = {"gh", "ij", "kl"}},
            New myStruct With {.Field1 = "klmno", .Field2 = 345, .Arr = {"mn", "op", "qr"}},
            New myStruct With {.Field1 = "pqrst", .Field2 = 456, .Arr = {"st", "uv", "wx"}}
        }

        WriteStructToFile(listOfMyStruct.ToArray, "C:\Temp\myStruct.bin")

        Dim listFromFile = ReadStructFromFile("C:\Temp\myStruct.bin").ToList
    End Sub

    Private Sub WriteStructToFile(ByVal arr() As myStruct, ByVal filePath As String)

        Using fs As New FileStream(filePath, FileMode.OpenOrCreate)
            Dim formatter As New BinaryFormatter()
            formatter.Serialize(fs, arr)
            fs.Close()
        End Using

    End Sub

    Private Function ReadStructFromFile(ByVal filePath As String) As myStruct()

        Using fs As New FileStream(filePath, FileMode.Open)
            Dim formatter As New BinaryFormatter()
            Dim structArr As myStruct() = CType(formatter.Deserialize(fs), myStruct())
            Return structArr
        End Using

    End Function

    <Serializable()>
    Private Structure myStruct
        <VBFixedString(5)> Public Field1 As String
        Public Field2 As String
        Public Arr As String()
    End Structure
End Class
 
Back
Top