I have several quesions about reading/writing structures from/to files.
In a scenario when I open a data file having its own header and variable data fields I create a structure that represents a header consisting of 9 bytes:
Code:
Public Structure HeaderInfo
Public DataField1 As Integer
Public DataField2 As Byte
Public DateField3 As Integer
End Structure
I'm using this code for the time being:
vb.net Code:
Public Function ReadHeader(ByVal FileName As String) As HeaderInfo
Dim ReturnInfo As HeaderInfo
Try
Using br As New IO.BinaryReader(New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
With ReturnInfo
.DataField1 = br.ReadInt32()
.DataField2 = br.ReadByte()
.DataField3 = br.ReadInt32()
End With
br.Close()
End Using
Return ReturnInfo
Catch ex As Exception
Return Nothing
End Try
End Function
The first question is - can I fill the structure directly somehow? Some structures are very long and filling them this way will be tedious. For example, if I know the length of the structure I could read the needed number of bytes in a byte array and somehow marshal these bytes into the structure.
My second question:
I can use Marshal.PtrToStructure, but then I would need to get an IntPtr of my byte array. Is it the only option?
And the last question - I use <Serializable()> attribute for my structure. Am I doing it right? Should there be some other attributes?