Idiomatic C# deserialization of custom binary files?

那年仲夏 提交于 2019-12-11 00:55:05

问题


Greetings,

What is the most idiomatic way of performing serialization/deserialization 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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4908205/idiomatic-c-sharp-deserialization-of-custom-binary-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!