Search code examples
c#filebytefilestream

Find a sequence of bytes and return the start position


I have a large file, I need to search in it for a sequence of 7 bytes and return the position of that sequence in that files. I can't post any code because so far I was not able to write any decent code. Can anyone please point me in the right direction? Maybe is there a function that I don't know the existence of?

Example Given a file like that: enter image description here

I want to find the position of F8 1E 13 B9 E4 28 88 which in this case is at 0x21


Solution

  • Here's a nice extension method to do it:

    public static class ByteArrayExtensions
    { 
        public static int IndexOf(this byte[] sequence, byte[] pattern)
        {
            var patternLength = pattern.Length;
            var matchCount = 0;
    
            for (var i = 0; i < sequence.Length; i++) 
            {
                if (sequence[i] == pattern[matchCount])
                {
                    matchCount++;
                    if (matchCount == patternLength) 
                    {
                        return i - patternLength + 1;
                    }
                }
                else
                {
                    matchCount = 0;
                }
            }
    
            return -1;
        }
    }
    

    Then you can find it as follows:

    var bytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x010 };
    
    var index = bytes.IndexOf(new byte[] { 0x03, 0x04, 0x05 });