C#/.NET - Custom Binary File Formats - Where to Start?

前端 未结 5 1981
日久生厌
日久生厌 2021-02-03 13:33

I need to be able to store some data in a custom binary file format. I\'ve never designed my own file format before. It needs to be a friendly format for traveling between the C

5条回答
  •  半阙折子戏
    2021-02-03 13:42

    Suppose your format is:

        struct Format
        {
            struct Header // 1
            {
                byte a;
                bool b1, b2, b3, b4, b5, b6, b7, b8;
                string name;
            }
            struct Container // 1...*
            {
                MyTypeEnum Type;
                byte[] data;
            }
        }
    
        enum MyTypeEnum
        {
            Sound,
            Video,
            Image
        }
    

    Then I'd have a sequential file with:


    byte // a

    byte // b

    int // name size

    char[] // name (which has the size specified above, remember a char is 16 bits in .NET)

    int // MyTypeEnum type

    int // data size

    byte[] // data (which has the size specified above)


    Then you can repeat the last three lines as many as you want.

    To read you use the BinaryReader which has support for reading bytes, integers and series of bytes. There is also a BinaryWriter.

    Further, remember that Microsoft .NET (thus on a Windows/Intel machine) is little-endian. So is the BinaryReader and BinaryWriter.

提交回复
热议问题