该 My.Computer.FileSystem
对象提供 ReadAllBytes
从二进制文件读取的方法。
读取二进制文件
ReadAllBytes
使用该方法,该方法将文件的内容作为字节数组返回。 此示例从文件C:/Documents and Settings/selfportrait.jpg
读取 。Dim bytes = My.Computer.FileSystem.ReadAllBytes( "C:/Documents and Settings/selfportrait.jpg") PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))
对于大型二进制文件,可以使用 Read 对象的方法 FileStream 一次仅从文件中读取指定数量。 然后,您可以限制每次读取操作加载到内存中的文件数据量。 以下代码示例将复制文件,并允许调用方指定每次读取操作将文件读入内存的数量。
' This method does not trap for exceptions. If an exception is ' encountered opening the file to be copied or writing to the ' destination ___location, then the exception will be thrown to ' the requestor. Public Sub CopyBinaryFile(ByVal path As String, ByVal copyPath As String, ByVal bufferSize As Integer, ByVal overwrite As Boolean) Dim inputFile = IO.File.Open(path, IO.FileMode.Open) If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then My.Computer.FileSystem.DeleteFile(copyPath) End If ' Adjust array length for VB array declaration. Dim bytes = New Byte(bufferSize - 1) {} While inputFile.Read(bytes, 0, bufferSize) > 0 My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True) End While inputFile.Close() End Sub
可靠的编程
以下情况可能会导致异常:
路径对于以下原因之一无效:它是一个零长度字符串,它只包含空格,它包含无效字符,或者它是设备路径(ArgumentException)。
路径无效,因为它是
Nothing
(ArgumentNullException)。该文件不存在(FileNotFoundException)。
该文件由另一个进程使用,或者发生 I/O 错误(IOException)。
路径超过系统定义的最大长度(PathTooLongException)。
路径中的文件或目录名称包含冒号(:)或格式无效(NotSupportedException)。
没有足够的内存将字符串写入缓冲区(OutOfMemoryException)。
用户缺少查看路径所需的权限(SecurityException)。
不要根据文件的名称决定文件的内容。 例如,文件Form1.vb可能不是 Visual Basic 源文件。
在应用程序中使用数据之前验证所有输入。 文件的内容可能不是预期内容,从文件读取的方法可能失败。