在VB.Net中,我用BinaryReader打开一个文件..
我需要在文件中找到一些Hex值,如果找到它们,它会返回第一个Byte的偏移地址。
有可能吗?怎么能实现这个呢?谢谢
修改
我目前的代码:
Private Function findOffset()
Using reader As New BinaryReader(File.Open(filename, FileMode.Open))
' Loop through length of file.
Dim pos As Integer = 0 ' <== THIS IS THE OFFSET
Dim length As Integer = reader.BaseStream.Length
Do While pos < length
' Read the integer.
Dim value As Byte = reader.ReadByte()
If value = CByte(&H41) Then
Return pos
Exit Do
End If
' Add length of integer in bytes to position.
pos += 1
Loop
End Using
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(Hex(findOffset()).ToString.PadLeft(6, "0"c))
End Sub
我要做的是:
例如,我打开一个文件,在用Hex编辑器打开的文件中,我看到有一些Hex值,41,42,43,44
。我需要查找这些值,然后返回它们所在的偏移地址。
使用我当前的代码它可以工作,但我只能找到1Byte,我需要找到超过1 .. 我可能需要找到1kb或更多的数据!
我这样做是为了在一些bin文件中找到空闲空间。所以例如我需要10Byte的可用空间。在Hex heditor中是FF,FF,FF,FF,FF,FF,FF,FF,FF,FF
,我需要找到并返回第一个空字节的偏移量。
编辑2
这是第一行代码。
Private Function findOffset(query as Byte())
Using reader As New BinaryReader(File.Open(filename, FileMode.Open))
Dim startOffset = 80
Dim length As Integer = reader.BaseStream.Length - startOffset
reader.BaseStream.Position = startOffset
If query.Length <= length Then
...
但是不起作用..它告诉我自由空间从十进制偏移00000047
我在这里做错了,我不明白你的意思
修改“长度”变量“length = length - startOffset”
答案 0 :(得分:1)
Using reader As New BinaryReader(File.Open("file.bin", FileMode.Open))
' Loop through length of file.
Dim pos As Integer = 0 ' <== THIS IS THE OFFSET
Dim length As Integer = reader.BaseStream.Length
While pos < length
' Read the integer.
Dim value As Byte = reader.ReadByte()
If value == 123 Then
return pos
End If
' Write to screen.
Console.WriteLine(value)
' Add length of integer in bytes to position.
pos += 1
End While
End Using
从http://www.dotnetperls.com/binaryreader-vbnet
略微修改编辑要搜索值数组,您必须遍历函数内部的数组。
Private Function findOffset(query as Byte())
Using reader As New BinaryReader(File.Open(filename, FileMode.Open))
Dim length As Integer = reader.BaseStream.Length
If query.Length <= length Then
' process initial (first) search
Dim values As Byte() = reader.ReadBytes(query.Length)
Dim found As Boolean = False
For fnd = 0 To query.Length - 1
If values(fnd) <> query(fnd) Then
found = False
Exit For
End If
found = True
Next fnd
If found = True Then
Return 0
Else ' keep searching the rest of the binary stream
For pos = query.Length To length - 1
' shift values over 1, [1,2,3,4] => [2,3,4,4]
Array.Copy(values, 1, values, 0, values.Length - 1)
' put the next new byte at the end
values(values.Length - 1) = reader.ReadByte()
For fnd = 0 To query.Length - 1
If values(fnd) <> query(fnd) Then
found = False
Exit For
End If
found = True
Next fnd
If found = True Then
Return pos - (query.Length - 1)
End If
Next pos
End If
End If
End Using
Return -1 ' not found
End Function
注意:我没有测试过上面的代码,因此可能存在语法错误。