1

I'm looking to find a large section of bytes within a file, remove them and then import a new large section of bytes starting where the old ones started.

Here's a video of the manual process that I'm trying to re-create in C#, it might explain it a little better: https://www.youtube.com/watch?v=_KNx8WTTcVA

I have only basic experience with C# so am learning as I go along, any help with this would be very appreciated!

Thanks.

1 Answer 1

1

Refer to this question: C# Replace bytes in Byte[]

Use the following class:

public static class BytePatternUtilities
{
    private static int FindBytes(byte[] src, byte[] find)
    {
        int index = -1;
        int matchIndex = 0;
        // handle the complete source array
        for (int i = 0; i < src.Length; i++)
        {
            if (src[i] == find[matchIndex])
            {
                if (matchIndex == (find.Length - 1))
                {
                    index = i - matchIndex;
                    break;
                }
                matchIndex++;
            }
            else
            {
                matchIndex = 0;
            }

        }
        return index;
    }

    public static byte[] ReplaceBytes(byte[] src, byte[] search, byte[] repl)
    {
        byte[] dst = null;
        byte[] temp = null;
        int index = FindBytes(src, search);
        while (index >= 0)
        {
            if (temp == null)
                temp = src;
            else
                temp = dst;

            dst = new byte[temp.Length - search.Length + repl.Length];

            // before found array
            Buffer.BlockCopy(temp, 0, dst, 0, index);
            // repl copy
            Buffer.BlockCopy(repl, 0, dst, index, repl.Length);
            // rest of src array
            Buffer.BlockCopy(
                temp,
                index + search.Length,
                dst,
                index + repl.Length,
                temp.Length - (index + search.Length));


            index = FindBytes(dst, search);
        }
        return dst;
    }
}

Usage:

byte[] allBytes = File.ReadAllBytes(@"your source file path");
byte[] oldbytePattern = new byte[]{49, 50};
byte[] newBytePattern = new byte[]{48, 51, 52};
byte[] resultBytes = BytePatternUtilities.ReplaceBytes(allBytes, oldbytePattern, newBytePattern);
File.WriteAllBytes(@"your destination file path", resultBytes)

The problem is when the file is too large, then you require a "windowing" function. Don't load all the bytes in memory as it will take up much space.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.