0

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.

level42
  • 946
  • 2
  • 13
  • 33

1 Answers1

1

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
Toadlips
  • 38
  • 4
  • This results in a "File in use" flag getting thrown up, and it writes 6 bytes to the file (deleting all of the contents). – level42 Aug 05 '15 at 03:06
  • Seems to be working once I cleaned up the code, let me test just a little bit further. – level42 Aug 05 '15 at 03:14
  • The above code has no statements which would write to a file...and if a "File in use" flag appeared, then that indicates it was unable to obtain access to the file for read or write operations. Are you running this against a file that is already open in another application? – Toadlips Aug 05 '15 at 03:15
  • Hi, I got this working great, thanks again. But I was wondering, how can I remove the hyphens from the output? I can't seem to find where it's being set anywhere. It's creating a problem when I try to convert the HEX into ASCII – level42 Aug 07 '15 at 16:58
  • Glad it's working! If the hyphens are giving trouble, you can replace the hyphen with something else, like this: `displayValue = BitConverter.ToString(value).Replace("-", " ")`. Also, if you would like to get the ASCII string directly from the byte array, you can do this: `displayValue = System.Text.Encoding.ASCII.GetString(value)`. – Toadlips Aug 08 '15 at 02:17