问题描述
我想先将一些旧文件转换为人类可读的类型,因此在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
然后致电
ReadFile(MyF, vSS1, SizeOf(TFSerialDocEx), nr1, nil);
所以我正在寻找一种使用小型程序来转换此文件的方法,我想用C#来实现,因为与C语言相比,与Delphi相比,我更熟悉C#..MFS文件是用二进制文件编写的,所以我需要将其转换为文本/字符串,我尝试了简单的二进制转换,但是还不行,因为在参数上似乎SizeOf Object很重要?还是
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?
推荐答案
广义上讲,我会考虑以下三种方法:
There broadly speaking are three approaches that I would consider:
1.用Delphi代码转换数据
由于您已经具有Delphi代码来读取数据和定义的结构,因此使用Delphi代码转换数据将是最简单和最快的.只需使用您现有的代码进行阅读,然后以易于阅读的形式输出.例如,使用内置的JSON库.
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.定义一个等效的格式化C#结构,并将二进制数据映射到该结构上
在C#中定义一个格式化的结构,该结构具有与放入磁盘的结构相同的二进制布局.如果打包了Delphi结构,则将使用 LayoutKind.Sequential
,并可能指定 Pack = 1
.您可能需要在某些成员上使用 MarshalAs
属性来实现二进制等效.然后从磁盘将结构读取到字节数组中.固定此数组,并在固定的对象地址上使用 Marshal.PtrToStructure
进行反序列化.现在您有了数据,可以随心所欲地编写它.
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.
可以在此处找到示例:从delphi打包记录中进行正确的结构布局
An example can be found here: Proper struct layout from delphi packed record
3.使用二进制阅读器逐个字段读取结构
可以使用 BinaryReader
从流中一次读取一个字段,而不是声明二进制兼容结构.诸如 Read
, ReadInt32
, ReadDouble
之类的方法调用可让您逐步处理记录.请记住,将按照声明Delphi记录的顺序来写入字段.如果原始记录是对齐的而不是打包的,则将需要跳过所有填充.同样,一旦您的数据可用于C#代码,就可以随意编写它.
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.
这篇关于从delphi读取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!