开发者

Idiomatic C# deserialization of custom binary files?

开发者 https://www.devze.com 2023-02-08 13:20 出处:网络
Greetings, What is the most idiomatic way of performing serialization/deserial开发者_开发技巧ization of binary custom formats? For example, how would you read a file with a set of headers specified i

Greetings,

What is the most idiomatic way of performing serialization/deserial开发者_开发技巧ization of binary custom formats? For example, how would you read a file with a set of headers specified in bytes (e.g. 4, 4, 16, 4, 8, 8, 4, 16) with no padding, with mixed integer/byte[] types?

In other words, how do you achieve the same level of control as in C when specifying a structure, without having to resort to sequences of Read/WriteBytes over a Stream?

Thanks.


Here's an article which illustrates one method to achieve this. But if you want ideomatic .NET then BinaryReader is the way to go. If the format is not imposed and you have control over it you could also use BinaryFormatter but what it produces is not interoperable.


Assuming that is a custom format, I would (and have) look to the XmlReader API; I would write a SomeFormatReader that rides a stream, and has a method for reading the next header. Once the caller has seen this return true (false meaning EOF), the caller should be able to access a property to check the data format that follows, and be able to call any of ReadInt32, ReadString, ReadSingle etc to handle each (following the rules of the binary format). In my case, my reader class also handles additional data buffering, etc.

You may then choose to wrap that with a secondary layer that uses type metadata and the newly-written reader to populate your object model (any of reflection, code-generation, meta-programming, etc). But creating a good standalone reader is he first hurdle.

0

精彩评论

暂无评论...
验证码 换一张
取 消