[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 319
  • Last Modified:

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!  
0
jploettner
Asked:
jploettner
1 Solution
 
gregoryyoungCommented:
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]) {
         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).

Cheers,

Greg Young
0
 
Expert1701Commented:
* 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;
  }
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now