Reputation: 153
I use this code to read full hex of file :
Dim bytes As Byte() = IO.File.ReadAllBytes(OpenFileDialog1.FileName)
Dim hex As String() = Array.ConvertAll(bytes, Function(b) b.ToString("X2"))
Can i only read like first X number of bytes and convert it to hex?
Thanks,
Upvotes: 3
Views: 6442
Reputation: 83
In a more advanced case with offset support I have found this code in an open source DLL file.
Function readX(ByVal file As String, ByVal offset As UInt64, ByVal count As UInt64) As Byte()
'hon Code 2023 (FUNCT v1.1.00)
Dim buffer() As Byte = New Byte(count - 1) {}
Using fs As New FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)
fs.Seek(offset, SeekOrigin.Begin)
fs.Read(buffer, 0, count)
End Using
Return buffer
End Function
A basic usage is
readX(file, offset, count)
E.g.
readX("test.txt", 2, 2)
It reads from the 2nd to 4th byte of the test.txt file.
Upvotes: 1
Reputation: 40403
There are a ton of ways of getting bytes from a file in .NET. One way is:
Dim arraySizeMinusOne = 5
Dim buffer() As Byte = New Byte(arraySizeMinusOne) {}
Using fs As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)
fs.Read(buffer, 0, buffer.Length)
End Using
The arraySizeMinusOne
is the max index of your array - so setting to 5 means you'll get 6 bytes (indices 0 through 5).
This is a popular way of reading through a large file, one chunk at a time. Usually you'll set your buffer at a reasonable size, like 1024 or 4096, then read that many bytes, do something with them (like writing to a different stream), then move on to the next bytes. It's similar to what you would do with StreamReader
when dealing with a text file.
Upvotes: 3