Search code examples
c#hexbinarywriter

Replacing byte in file


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".


Solution

  • 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.