首页 > 解决方案 > 在 vb.net 中找到搜索文本的字节位置

问题描述

我想在下面提供的代码中加入该代码,该代码可以让我知道搜索和找到的文本在文件中的字节位置!可能吗 ?预先感谢您为我提供帮助和知识。

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

标签: vb.netbyte

解决方案


我试过你的代码,它正确地找到了搜索字节的位置。
所以问题出在其他地方,这是由于代码在找到字节后并没有停止,而是一直持续到搜索到的缓冲区结束。
但此时变量 i 将始终等于终止循环的条件。

找到匹配项时,您需要添加一个简单的 Exit For

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

当然,如果您需要查找文件中的每个匹配项,而不仅仅是第一个匹配项,那么您需要终止循环并收集找到的偏移量。在这种情况下,您需要在进入文件循环时声明一个 List(Of Integer) 类型的变量

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 

推荐阅读