This should be simple! Read a File into a Byte Array

S

Shaun Merrill

Hey, here is my code. I am trying to read a file into a byte array. Please
show me how this can work.
Obviously I need to read into a dynamic array because it could read any
file. So why does VB.NET give me the ability to read into a Byte Array if
it doesn't allow me to use a variable sized array?

Dim i As Short = FreeFile()
FileSystem.FileOpen(i, Filename, OpenMode.Binary, OpenAccess.Read,
OpenShare.Default)
Dim iByteArray() As Byte
ReDim iByteArray(LOF(i))
FileSystem.FileGet(i, iByteArray, True)
FileSystem.FileClose(i)

This code bombs on FileGet(), throwing an EndOfStream exception "Unable to
read beyond the end of the stream."
Even if I use no Redim statement, I get "Cannot determine array type because
it is Nothing."

Obviously, the ArrayIsDynamic parameter is set to True. What am I doing
wrong?!?

~ Frustrated
 
L

Lucas Tam

Hey, here is my code. I am trying to read a file into a byte array.
Please show me how this can work.
Obviously I need to read into a dynamic array because it could read
any file. So why does VB.NET give me the ability to read into a Byte
Array if it doesn't allow me to use a variable sized array?

Dim i As Short = FreeFile()
FileSystem.FileOpen(i, Filename, OpenMode.Binary, OpenAccess.Read,
OpenShare.Default)
Dim iByteArray() As Byte
ReDim iByteArray(LOF(i))
FileSystem.FileGet(i, iByteArray, True)
FileSystem.FileClose(i)

This code bombs on FileGet(), throwing an EndOfStream exception
"Unable to read beyond the end of the stream."
Even if I use no Redim statement, I get "Cannot determine array type
because it is Nothing."

Obviously, the ArrayIsDynamic parameter is set to True. What am I
doing wrong?!?


I think you need to set the preserve keyword:

Redim preserve ibyteArray(LOF(i))

Also, you should be dimming LOF(i) - 1, because arrays are 0-based (so a
byte array of 19999 is really 20000 bytes)
 
C

Cor Ligthert

Shaun,

This should be enough

\\\
Dim fs As New IO.FileStream(FilePath, _
IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
abyt = br.ReadBytes(CInt(fs.Length))
br.Close()
///

I hope this helps?

Cor
 
H

Herfried K. Wagner [MVP]

Cor Ligthert said:
Dim fs As New IO.FileStream(FilePath, _
IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
abyt = br.ReadBytes(CInt(fs.Length))

.... for files with length <= 'Int32.MaxValue'.

;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top