Search code examples
vb.netfilestreambinaryreader

Finding HEX value at a specific offset in VB.net


I'm trying to figure out how to read a section of bytes (Say 16) starting at a specific address, say 0x2050. I'd like to get the 16 bits output in hex values into a label.

I've been trying to figure out BinaryReader, and FileStreams but I'm not entirely sure what the difference is, or which one I should be using.

*I've seen a lot of threads mentioning file size could be an issue, and I'd like to point out that some files I'll be checking may be up to 4gb in size.


I've tried the following:

Dim bytes() As Byte = New Byte(OpenedFile.Length) {}
ListBox1.Items.Add(Conversion.Hex(OpenedFile.Read(bytes, &H2050, 6)))

But this simply writes 6 bytes to the file, and I'm not sure why. There is no output in the listbox.


Solution

  • How about something like the following?:

    Sub Main()
        Dim pos As Long = 8272
        Dim requiredBytes As Integer = 2
        Dim value(0 To requiredBytes - 1) As Byte
        Using reader As New BinaryReader(File.Open("File.bin", FileMode.Open))
            ' Loop through length of file.
            Dim fileLength As Long = reader.BaseStream.Length
            Dim byteCount As Integer = 0
            reader.BaseStream.Seek(pos, SeekOrigin.Begin)
            While pos < fileLength And byteCount < requiredBytes
                value(byteCount) = reader.ReadByte()
                pos += 1
                byteCount += 1
            End While
        End Using
    
        Dim displayValue As String
        displayValue = BitConverter.ToString(value)
    End Sub