0

Most of the time when we read the file stream into a byte array, we would write the following code:-

 Dim inputStream As New System.IO.FileStream(filePath, IO.FileMode.Open)
 Dim fileLength As Integer= CType(inputStream.Length, Integer)
 Dim input(fileLength) As Byte

 Using inputStream
     inputStream.Read(input, 0, fileLength)
 End Using

But here we have to convert Length into an integer type (line 2 of the code above) since we cannot declare a byte array using the long data type (with option strict on). Is this a good practice? What is the work around for this problem?

1 Answer 1

2

The good practice is to use File.ReadAllBytes instead of the whole thing:

Dim input = File.ReadAllBytes(filePath)

By the way, if your file is going to be that large (more than 4 GB), you wouldn't want to load it all at once in a byte array as it'll take up 4GB RAM (and in a 32 bit managed process, you can't have it at all, even if you have got more RAM).

Sign up to request clarification or add additional context in comments.

4 Comments

I think you mean File.Read Not ReadAllBytes ;)
@Deviant: No, there's no File.Read method. Actually, the whole code snippet in the OP can be replaced with bytes = File.ReadAllBytes(path). The second paragraph of the answer is started with "by the way" and is a separate entity ;)
I was assuming that since he had broken into the territory of using longs for Stream.Read() // which is what I meant with File.Read ... I was thinking he was having trouble with large files ... so your response seemed backwards to me :/
I actually mean you shouldn't think about loading large files in memory all at once. And if you are coding that snippet, you should replace it with a single line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.