vb.net - 在 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
解决方案
我试过你的代码,它正确地找到了搜索字节的位置。
所以问题出在其他地方,这是由于代码在找到字节后并没有停止,而是一直持续到搜索到的缓冲区结束。
但此时变量 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
推荐阅读
- java - 有什么方法可以 SFTP 生成文件名的文件包括 yyyyMMddHHmmss
- c# - 如何在本地系统应用程序中使用 RegOpenKeyEx?
- haskell - 为什么这个 Haskell 类型的强制不能编译?
- python - 如何在单个图表中绘制实时图表?
- java - 如何在春季安全中为每个人忽略一些资源/网址?
- reactjs - MobX + React Router 私有路由重定向
- ubuntu - 在具有预装窗口的系统上安装 ubuntu 18.04 时的“efi”分区
- sql - 通过 shell 脚本执行合并时出错
- deep-learning - YOLO3 不能在 GTX 2080 TI 上运行?
- multithreading - 如何将期货中的函数输出传递给新函数?