HyperX
HyperX

Reputation: 1211

Reading binary file from delphi

I want to transition some old files first to human readable type, so in Delphi code is following:

OpenFileWriteRA(MyF, dd+'invoice.mfs', SizeOf(TFSerialDocEx)) then

and then calling

ReadFile(MyF, vSS1, SizeOf(TFSerialDocEx), nr1, nil);

So i am looking for a way to conver this files using with small programm i want to make it with C#, as i am more fammiliar with C# than with Delphi. .MFS file is written in binary, so what would i need to convert this to text/string, i tryed with simple binary convert but it was not ok, as it seems SizeOf Object at paramters is big thing here or?

Upvotes: 1

Views: 1571

Answers (1)

David Heffernan
David Heffernan

Reputation: 613441

There broadly speaking are three approaches that I would consider:

1. Transform data with Delphi code

Since you already have Delphi code to read the data, and structures defined, it will be simplest and quickest to transform the data with Delphi code. Simply read it using your existing code and then output in human readable form. For instance using the built in JSON libraries.

2. Define an equivalent formatted C# structure and blit the binary data onto that structure

Define a formatted structure in C# that has identical binary layout to the structure put to disk. This will use LayoutKind.Sequential and perhaps specify Pack = 1 if the Delphi structure is packed. You may need to use the MarshalAs attribute on some members to achieve binary equivalence. Then read the structure from disk into a byte array. Pin this array, and use Marshal.PtrToStructure on the pinned object address to deserialize. Now you have the data, you can write it how you please.

An example can be found here: Proper struct layout from delphi packed record

3. Read the structure field by field with a binary reader

Rather than declaring a binary compatible structure you can use a BinaryReader to read from a stream one field at a time. Method calls like Read, ReadInt32, ReadDouble, etc. let you work your way through the record. Remember that the fields will have been written in the order in which the Delphi record was declared. If the original record is aligned rather than packed you will need to step over any padding. Again, once you have the data available to your C# code you can write it as you please.

Upvotes: 4

Related Questions