Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'
i get the error in following code
Function ReadFile(ByVal sPath As String) As Byte
Dim data As Byte
data = Nothing
Dim fInfo As FileInfo
fInfo = New FileInfo(sPath)
Dim numBytes As Long
numBytes = fInfo.Length
Dim fStream As FileStream
fStream = New FileStream(sPath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader
br = New BinaryReader(fStream)
data = Convert.ToByte(br.ReadBytes(numBytes)) `getting error on this line`
Return data
End Funct开发者_开发知识库ion
The ReadBytes function returns a byte array which you are passing to the Convert.ToByte function which throws an exception at runtime because you cannot convert an array of multiple bytes to a single byte. Depending on what you are trying to accomplish the actions to fix the problem will vary.
- You have defined ReadFile to return a single byte, as in Byte.
- ReadBytes returns a byte array, as in Byte().
- You cannot convert a Byte() to a Byte.
- Byte(0) = Byte
- Byte <> Byte()
- Convert.ToByte takes an Object.
- Visual Basic .NET with Option Strict Off will try to convert Byte(), the Object you are passing to Convert.ToByte, into a Byte by calling the System.IConvertible interface on Byte() array, which will throw an exception because an Array does not implement this interface.
From your function implementation, it is obvious that you want to return all bytes. Therefore, change ReadFile to return Byte() and remove the ToByte method call.
精彩评论