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

北战南征 提交于 2019-12-04 21:18:25

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:

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