Reading mid part of file

I've been using vb6 to print a block of data from the middle of a file. ...
Dim Chunk As String * 100
Open files(i) For Binary As #ff1
MyLen = LOF(ff1)
Get #ff1, MyLen / 2, Chunk
For i = 1 To 100
f = Asc(Mid(ff, i, 1))
Debug.Print Right("00" & Hex(f), 2); " ";
next
Close # ff1
... I would like to now use this in VS keeping the same output
Using fs As New FileStream(filePath, FileMode.Open, FileAccess.Read)
' Get the total length of the file
Dim fileLength As Long = fs.Length
' Calculate the midpoint (VB6 was using LOF/2, the equivalent to fileLength / 2 in VB.NET ?)
Dim midpoint As Long = fileLength \ 2
' Read a block of bytes starting from the midpoint
' read 100 bytes
Dim buffer(99) As Byte
fs.Seek(midpoint, SeekOrigin.Begin) ' Move to midpoint
fs.Read(buffer, 0, buffer.Length)
' Print the read bytes in hex
For Each b As Byte In buffer
Debug.Write(b.ToString("X2") & " ")
Next
Debug.WriteLine("")
End Using
There are about 200 files, some which have matched, but never all.
The Mid starting point is non-consistent.
Some factors may be (but cannot confirm or find a pattern)
VS file read is 0-Based and VB6 is 1-based
LOF/2 can often be a non integer
Can anyone suggest why the midpoint isn't consistent and the same for both procedures?
Answer
In VB6 you should use chunk
instead of ff
- I haven't run your code, but using ff
should not work. Do this in VB6:
f = Asc(Mid(chunk, i, 1))
If the file length is odd, VB6 will start one byte later than VB.NET, due to 1-indexed vs 0-indexed. To get the same result, do this in VB.NET:
Dim midpoint As Long = (fileLength + 1) \ 2
You use two different methods of division to calculate the midpoint, floating point division (/
) and integer division (\
). You should use integer division in both languages, for what you are trying to achieve.
And in VB6 you don't print a newline after the loop, before you close the file, like you do in VB.NET. Add this line before you close the file to VB6:
Debug.Print ""
I'd also check if the length of the file is one or zero bytes long; and print nothing if that's the case.
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles