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?
但是在这里我们必须将Length转换为整数类型(上面代码的第2行),因为我们不能使用long数据类型声明一个字节数组(选项严格打开)。这是一个好习惯吗?这个问题的解决方法是什么?
1 个解决方案
#1
The good practice is to use File.ReadAllBytes
instead of the whole thing:
好的做法是使用File.ReadAllBytes而不是整个事情:
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).
顺便说一句,如果你的文件将是那么大(超过4 GB),你不希望在一个字节数组中一次性加载它,因为它将占用4GB RAM(并在32位管理中进程,即使你有更多的内存,你根本无法拥有它。
#1
The good practice is to use File.ReadAllBytes
instead of the whole thing:
好的做法是使用File.ReadAllBytes而不是整个事情:
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).
顺便说一句,如果你的文件将是那么大(超过4 GB),你不希望在一个字节数组中一次性加载它,因为它将占用4GB RAM(并在32位管理中进程,即使你有更多的内存,你根本无法拥有它。