BinaryFormatter in C# a good way to read files?

Posted by mr-pac on Stack Overflow See other posts from Stack Overflow or by mr-pac
Published on 2010-05-27T08:31:04Z Indexed on 2010/05/27 8:41 UTC
Read the original article Hit count: 223

Filed under:
|

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 approach 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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET