Read variable string size from binary (VB6 vs. C #)

I have a binary file with the following contents:

alt text

The following code is used to read this content in an old VB6 program:

Private Type tpClient Firstname As String LastName As String Birth As String Adres As String Geslacht As String IDNummer As Long SSNummer As String DatabaseID As Long Telefoon1 As String Telefoon2 As String End Type Open strFilePath For Random Access Read As #intFileNumber Get #intFileNumber, 1, ClientData ' ClientData is of type tpClient 

Now I'm trying to read this using my new C # program:

 [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct PatientStruct { [MarshalAs(UnmanagedType.BStr)] public string FirstName; [MarshalAs(UnmanagedType.BStr)] public string LastName; [MarshalAs(UnmanagedType.BStr)] public string BirthDate; [MarshalAs(UnmanagedType.BStr)] public string Address; [MarshalAs(UnmanagedType.BStr)] public string Gender; [MarshalAs(UnmanagedType.BStr)] public string IdNumber; [MarshalAs(UnmanagedType.BStr)] public string SsNumber; [MarshalAs(UnmanagedType.BStr)] public string DatabaseId; [MarshalAs(UnmanagedType.BStr)] public string Telephone1; [MarshalAs(UnmanagedType.BStr)] public string Telephone2; } byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); T stuff = (PatientStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); 

However, I get an AccessViolationException when I call Marshal.PtrToStructure.

Any suggestions?

0
source share
2 answers

First of all, your structure should not be a structure in general, but a class. Structures are designed for small immutable types that represent a single value.

Creating a data type marshal exactly the way you want is very difficult, and since you are not doing interop, you really don't need to sort. It’s easier to just use BinaryReader to read data from a file.

Simple data types can be read immediately, and rows can be read as follows:

 string value = reader.ReadChars(reader.ReadShort()); 

Specify a suitable single-byte encoding when opening the reader, for example, windows-1252.

+2
source

Marshal.PtrToStructure expects buffer be filled with line pointers. I do not think that Marshal can be used to do what you want.

Instead, you need to determine the format of the binary file and write the code for this manually. Take a look at the BinaryReader class.

Edit: If you are stuck, you can add a link to Microsoft.VisualBasic.dll and use FileSystem.FileGetObject . This behaves the same as the Get keyword in VB6.

+5
source

All Articles