Code:
''' <summary>
''' Gets the offsets of a specified byte array in a file.
''' </summary>
''' <param name="file">The file to search in.</param>
''' <param name="bytes">The bytes to search for.</param>
''' <returns>A list containing the offsets for the byte pattern specified.</returns>
Public Shared Function GetOffsets(ByVal file As String, ByVal bytes As Byte()) As List(Of Long)
Dim ret As New List(Of Long)()
Using s As Stream = New FileStream(file, FileMode.Open)
Using br As New BinaryReader(s)
While True
Try
' Save the current position so we can add it
' if this offset is the spot we want.
' Also so we can go back to here, if it's not.
Dim pos As Long = br.BaseStream.Position
' Read in the same amount of bytes that we have
' in the bytes param.
Dim ba As Byte() = br.ReadBytes(bytes.Length)
Dim ok As Boolean = True
' Small error check here.
If bytes.Length = ba.Length Then
For i As Integer = 0 To bytes.Length - 1
If ba(i) <> bytes(i) Then
ok = False
' Jump out immediately.
' It's not what we want, so there's no need to check more.
Exit For
End If
Next
End If
If ok Then
' Add the position we got these 4 bytes from.
ret.Add(pos)
End If
' Since the BinaryReader has jumped from pos to (pos + bytes.Length)
' we need to go back to where we were, plus 1 offset to read again.
br.BaseStream.Position = pos + 1
Catch generatedExceptionName As EndOfStreamException
' End of file
Exit Try
End Try
End While
End Using
End Using
Return ret
End Function
You can now just use
Code:
Public Sub test()
Dim bytes As Byte() = New Byte() {44, 66, 34, 25}
Dim offsets As List(Of Long) = GetOffsets("C:\MyFileToCheck.extension", bytes)
' Do whatever with the offsets here.
End Sub
Let me know if you have any issues.
Of course, you need to import the proper namespaces. (System.IO, and System.Collections.Generic, probably System as well.)