C#: Write values into Binary (.bin) file format

左心房为你撑大大i 提交于 2019-12-13 12:22:35

问题


So lets say I have the following values:

HEADER01    48 45 41 44 45 52 30 31
06/17/14    30 36 2F 31 37 2F 31 34
1.0         31 2E 30

0x0000      00
0x0027      27
0x0001      01
0x0001      01
0x0001      01
0x0001      01
0x0028      28

192         C0
168         A8
1           01
1           01
  • The first 3 values are STRINGS, should be converted to ASCII HEX values, then written in the .bin file

  • The next 7 values are HEX, should be written AS-IS in the .bin file

  • The last 4 values are INTEGERS, should be converted to HEX, then written in the .bin file

    OUTPUT (.bin) file should look something like this:

    00000000  48 45 41 44 45 52 30 31  30 36 2F 31 37 2F 31 34
    00000010  31 2E 30 00 27 01 01 01  01 28 C0 A8 01 01 00 00
    00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00
    

Is it possible to create a (.bin) file like this using C# .NET?

I tried BinaryWriter, StreamWriter but for some reason all the values are written as HEX strings not as I want them.


回答1:


Using BinaryWriter is the correct solution.

Don't fall to the temptation of using the BinaryWriter.Write(String) overload - it prefixes the string with a single-byte length, which is not what you want.

Also note that I've explicitly cast each value to a (byte). If I hadn't done this, the compiler would have selected the Write(int) overload, writing 4 bytes to the file.

class Program
{
    static void Main(string[] args)
    {
        using (var s = File.OpenWrite("temp.bin")) {
            var bw = new BinaryWriter(s);

            bw.Write(Encoding.ASCII.GetBytes("HEADER01"));
            bw.Write(Encoding.ASCII.GetBytes("06/17/14"));
            bw.Write(Encoding.ASCII.GetBytes("1.0"));

            bw.Write((byte)0x00);
            bw.Write((byte)0x27);
            bw.Write((byte)0x01);
            bw.Write((byte)0x01);
            bw.Write((byte)0x01);
            bw.Write((byte)0x01);
            bw.Write((byte)0x28);

            bw.Write((byte)192);
            bw.Write((byte)168);
            bw.Write((byte)1);
            bw.Write((byte)1);
        }
    }
}

Result:



来源:https://stackoverflow.com/questions/24357982/c-write-values-into-binary-bin-file-format

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