views:

222

answers:

1

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?

+2  A: 

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).

Mehrdad Afshari
I think you mean File.Read Not ReadAllBytes ;)
Chad Grant
@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 ;)
Mehrdad Afshari
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 :/
Chad Grant
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.
Mehrdad Afshari