user265889
user265889

Reputation: 667

Replace Series Of Bytes in File

I'm making a program that will patch upk files to replace "4f 4c 44 6f 6f 72" with "4f 4c 52 6f 6f 72" in about 186 files ("4f 4c 44 6f 6f 72" has multiple occurences in each file).

I've seen a lot of guides on how to do this but they all require an offset of where the original bytes are which means I would need about 28 offsets for each file which would take way too long...

What would be the best way to do this?

Upvotes: 1

Views: 197

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

If each file is small enough to fit RAM you can try reading the entire file, modifing it and writing back:

  private static IEnumerable<int> Offsets(byte[] data, byte[] toFind) {
    for (int i = 0; i <= data.Length - toFind.Length; ++i) {
      bool matched = true;

      for (int j = 0; j < toFind.Length; ++j)
        if (data[i + j] != toFind[j]) {
          matched = false;

          break;  
        }

      if (matched)
        yield return i; 
    }
  }

  private static void ModifyFile(String path) {
    byte[] toFind = new byte[] {0x4f, 0x4c, 0x44, 0x6f, 0x6f, 0x72 };

    byte[] data = File.ReadAllBytes(path);

    foreach(var offset in Offsets(data, toFind))
      data[offset + 2] = 0x52; // we want just one byte to update

    File.WriteAllBytes(path, data); 
  }

Upvotes: 1

Related Questions