claudebl
claudebl

Reputation: 75

Position of the byte at which the searched text is found in vb.net

I would like to incorporate in the code provided below, the code which would allow me to know the position in bytes in the file, of the searched and found text! Is it possible ? Thank you in advance for giving me your help and your knowledge.

Dim a As Integer

a = 1
For Each filename In list

    Sun j, i As Integer
    Dim ByteBuffer As Byte () = File.ReadAllBytes (filename)
    Dim StringBytes As Byte () = System.Text.Encoding.UTF8.GetBytes (matches)
    For i = 0 To ByteBuffer.Length - StringBytes.Length

        If ByteBuffer (i) = StringBytes (0) Then
            j = 1

            While j <StringBytes.Length AndAlso ByteBuffer (i + j) = StringBytes (j)
                j + = 1
            End While

            If j = StringBytes.Length Then MsgBox ("String was found at offset {0}", i)

        End If
    Next

    ListView1.Items.Add (System.IO.Path.GetFileName (filename))
    ListView1.Items (a - 1) .SubItems.Add (i)
    ListView1.Items (a - 1) .SubItems.Add (Convert.ToInt32 (i / 2987))
    a + = 1

Next

Upvotes: 1

Views: 146

Answers (1)

Steve
Steve

Reputation: 216293

I have tried your code and it finds correctly the position of the searched bytes.
So the problem is elsewhere and it is caused by the fact that the code doesn't stop after finding the bytes but it continues until the end of the buffer searched.
But at that point the variable i will be always equal to the condition that terminates the loop.

You need to add a simple Exit For when you find the match

If j = StringBytes.Length Then 
    MsgBox ("String was found at offset {0}", i)
    
    ' This stops the loop over the current file and the variable i is pointing to the offset searched
    Exit For
End if

Of course, if you need to find every match in the file and not just the first then you need to terminate the loop and collect the offsets found. In this case you need a variable of type List(Of Integer) declared when you enter the file loop

Sun j, i As Integer
Dim ByteBuffer As Byte () = File.ReadAllBytes (filename)
Dim StringBytes As Byte () = System.Text.Encoding.UTF8.GetBytes (matches)
Dim offsets as List(Of Integer) = new List(Of Integer)
For i = 0 To ByteBuffer.Length - StringBytes.Length

    If ByteBuffer (i) = StringBytes (0) Then
        j = 1

        While j <StringBytes.Length AndAlso ByteBuffer (i + j) = StringBytes (j)
            j + = 1
        End While

        If j = StringBytes.Length Then 
           MsgBox ("String was found at offset {0}", i)
           offsets.Add(i)
        End if
    End If
Next
if offsets.Count > 0 Then
    ListView1.Items.Add (System.IO.Path.GetFileName (filename))
    ListView1.Items (a - 1).SubItems.Add (string.Join(" >", offsets))
    a + = 1
End If 

Upvotes: 1

Related Questions