开发者

BinaryFormatter in C# a good way to read files?

I want to read a binary file which was created outside of my program. One obvious way in C# to read a binary file is to define class representing the file and then use a BinaryReader and read from the file via the Read* methods and assign the return values to the class properties.

What I don't like with the approa开发者_如何转开发ch is that I manually have to write code that reads the file, although the defined structure represents how the file is stored. I also have to keep the order correct when I read.

After looking a bit around I came across the BinaryFormatter which can automatically serialize and deserialze object in binary format. One great advantage would be that I can read and also write the file without creating additional code. However I wonder if this approach is good for files created from other programs on not just serialized .NET objects. Take for example a graphics format file like BMP. Would it be a good idea to read the file with a BinaryFormatter or is it better to manually and write via BinaryReader and BinaryWriter? Or are there any other approaches which suit better? I'am not looking for concrete examples but just for an advice what is the best way to implement that.


You'd have to be very VERY lucky to find an external file format that happened to map perfectly to the format the BinaryFormatter puts out. The BinaryFormatter obviously adds information on the types/things you're serializing, as well as the data itself, whereas a "normal" binary file format will generally be "these bytes are this, then these bytes are this".

When I've done this in the past (reading SWF headers springs to mind recently) I've always just used a file stream and processed/mapped it manually.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜