Eric Bergman
Eric Bergman

Reputation: 1443

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

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

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.

Upvotes: 1

Views: 3484

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

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: Hex editor output

Upvotes: 5

Related Questions