1

I'm trying to replace certain bytes from a file with some other specific bytes, but have a problem with my binary writer replacing too many bytes. What is wrong in my code?

using (BinaryWriter bw = 
    new BinaryWriter(File.Open(fileName, 
        FileMode.Open)))
{
    bw.BaseStream.Position = 0x3;
    bw.Write(0x50);
}

This was supposed to change the letter "E" (hex 0x45) with the letter "P", but instead changes that byte and 3 more bytes; from "45 30 31 FF" to "50 00 00 00". I would like to keep the "30 31 FF", only change "45" to "50".

Seregon85
  • 13
  • 3
  • You might want to check this post about short notations: https://stackoverflow.com/questions/5820721/c-sharp-short-long-int-literal-format#5820772 – Stefan Jul 04 '17 at 11:12

2 Answers2

4

Basically you don't want or need to use BinaryWriter for this. You're calling BinaryWriter.Write(int) which is behaving exactly as documented.

Just use FileStream to write a single byte:

using (var stream = File.Open(fileName))
{
    stream.Position = 3;
    stream.WriteByte(0x50);
}

Simpler, easier to read (it's obviously only writing a single byte), and does what you want.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Because method Write actually write int (4 bytes). You should convert your value to byte type. bw.Write((byte)0x50);

Ivan R.
  • 1,875
  • 1
  • 13
  • 11