Visual Basic 2005 - 讀取二進位檔的演進過程

摘要:Visual Basic 2005 - 讀取二進位檔的演進過程

在過去,我們會使用下列寫法來讀取二進位檔:

Dim fs As FileStream = New FileStream(ImageFilePath, FileMode.Open, FileAccess.Read)

Dim br As BinaryReader = New BinaryReader(fs)

Dim photo() As Byte = br.ReadBytes(fs.Length)

br.Close()
fs.Close()

自從 Visual Basic 2005 提供了 Using...End Using 之後,我們會改寫如下:

Dim photo As Byte()

Using fs As FileStream = New FileStream(ImageFilePath, FileMode.Open, FileAccess.Read)

     Using br As BinaryReader = New BinaryReader(fs)

         photo = br.ReadBytes(fs.Length)

     End Using

End Using

但是別忘了,Visual Basic 2005 還提供了一個更便利的 My,所以,最簡易的寫法應該如下喔

Dim photo As Byte()

photo = _
  My.Computer.FileSystem.ReadAllBytes(ImageFilePath)