Reputation: 1443
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.
Upvotes: 1
Views: 3484
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:
Upvotes: 5