How to replace hexadecimal value in a binary file?

Asked

Viewed 853 times

8

Can you tell me how to replace the Hex value of a file with C#? Example: replace 62 61 72 ("bar") for 66 6F 6F ("foo").

  • You can’t turn this into a string to replace it ?

  • 2

    You’re talking about a binary file?

  • Yes, The file is binary.

  • Can’t open as text file and make the change with the replace?

  • I’m a beginner in C#, I tried to use Binarywriter to edit but I couldn’t.

  • Have a reference to the size of these binary files ?

Show 1 more comment

3 answers

4

You will need to process the bytes manually in the case of a binary file:

byte[] findBytes = { 0x62, 0x61, 0x72 };
byte[] replaceBytes = { 0x66, 0x6F, 0x6F };
List<byte> result;

using (var file = File.OpenRead(@"...origem..."))
{
    var allBytes = new byte[(int)file.Length];
    file.Read(allBytes, 0, (int)file.Length);
    result = new List<byte>(allBytes.Length);

    for (int itFile = 0; itFile < allBytes.Length; itFile++)
    {
        bool found = !findBytes
            .Where((t, i) => (i + itFile >= allBytes.Length)
                || (t != allBytes[i + itFile])).Any();

        if (found)
        {
            result.AddRange(replaceBytes);
            itFile += findBytes.Length - 1;
        }
        else
            result.Add(allBytes[itFile]);
    }
}

using (var file = File.Open(@"...destino...", FileMode.Create))
    file.Write(result.ToArray(), 0, result.Count);

This is a very crude implementation... that reads all bytes of the source and does all the processing in memory... in the case of very long files, you will probably have to subdivide the file and do the overwriting part by part.

1

There is an excellent explanation in an original Stackoverflow post in English:

https://stackoverflow.com/questions/3217732/how-to-edit-a-binary-files-hex-value-using-c-sharp

Translation adapted from the important part:

If you want to simply change the values of the bytes in the file, the most efficient approach in my opinion would be to open the file using a Filestream, find the appropriate position, and replace the bytes, as in the example below:

using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) {
    stream.Position = 0;
    stream.WriteByte(0x66);
    stream.WriteByte(0x6F);
    stream.WriteByte(0x6F);
}
  • But then he would have to know the position of the bytes he wants to replace.

-2

Try it like this: Hex p/ Decimal:

Convert.ToInt64(hexValue, 16);

Decimal p/ Hexadecimal:

string.format("{0:x}", decValue);
  • This shows how to convert from decimal to hexadecimal, but does not answer the question. If you can add the part of editing the file to the reply, your answer will be better accepted.

  • I misread his question. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.