How to edit a binary file's hex value using C#

I think this is best explained with a specific example. Here are the first 32 bytes of an executable file as shown in Visual Studio's hex editor:

00000000  4D 5A 90 00 03 00 00 00  04 00 00 00 FF FF 00 00
00000010  B8 00 00 00 00 00 00 00  40 00 00 00 00 00 00 00

Now a file is really just a linear sequence of bytes. The rows that you see in a hex editor are just there to make things easier to read. When you want to manipulate the bytes in a file using code, you need to identify the bytes by their 0-based positions. In the above example, the positions of the non-zero bytes are as follows:

Position  Value
--------  ------
  0        0x4D
  1        0x5A
  2        0x90
  4        0x03
  8        0x04
 12        0xFF
 13        0xFF
 16        0xB8
 24        0x40

In the hex editor representation shown above, the numbers on the left represent the positions of the first byte in the corresponding line. The editor is showing 16 bytes per line, so they increment by 16 (0x10) at each line.

If you simply want to take one of the bytes in the file and change its value, the most efficient approach that I see would be to open the file using a FileStream, seek to the appropriate position, and overwrite the byte. For example, the following will change the 0x40 at position 24 to 0x04:

using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) {
    stream.Position = 24;
    stream.WriteByte(0x04);
}

Tags:

C#

Hex

Binary

Edit