search large byte[] for the existiance of a smaller byte[] with C# and .NET 2.0

I'm reading a binary file into a byte array and need to search the bytes for patterns..

for file i read into:
byte[] fileBuffer = new byte[filesize];

and I'm trying to search for:
byte[] targetDLL = { 0x2E, 0x64, 0x6C, 0x6C, 0, 0 }; (and a few others)

A C#.NET 2.0 example of how to search the large file byte array for my smaller 'patterns' would be greatly appreciated!  
Who is Participating?
it is actually pretty simple ...

if just getting it right is important ...

for(int i=0;i<fileBuffer.Size;i++) {
    if(fileBuffer[i] == targetDLL[current]) {
         if(current == tagetDLL.Length) {
              Console.WriteLine("Found pattern at index " + (i - TargetDLL.Length).ToString());
    } else {
         current = 0;

if you are trying to optimize it to be fast I would use unmanaged code and a pointer to iterate through the byte arrays (much faster).


Greg Young
* Not for points, but I believe a minor change is required:

  if(current == targetDLL.Length) {
    Console.WriteLine("Found pattern at index " + (i - targetDLL.Length).ToString());
    current = 0;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.