Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top