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

Posted on 2006-05-09
Last Modified: 2012-05-05
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!  
Question by:jploettner
    LVL 37

    Accepted Solution

    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
    LVL 11

    Expert Comment

    * 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;

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
    Article by: Ivo
    C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    733 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    25 Experts available now in Live!

    Get 1:1 Help Now