从字节 [] 转换为文件

Convert From Byte[] to File

我使用以下函数将文件转换为 Byte()

Public Function FileToByteArray(ByVal _FileName As String) As Byte()
    Dim _Buffer() As Byte = Nothing

    Try
        ' Open file for reading
        Dim _FileStream As New System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)

        ' attach filestream to binary reader
        Dim _BinaryReader As New System.IO.BinaryReader(_FileStream)

        ' get total byte length of the file
        Dim _TotalBytes As Long = New System.IO.FileInfo(_FileName).Length

        ' read entire file into buffer
        _Buffer = _BinaryReader.ReadBytes(CInt(Fix(_TotalBytes)))

        ' close file reader
        _FileStream.Close()
        _FileStream.Dispose()
        _BinaryReader.Close()
    Catch _Exception As Exception
        ' Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
    End Try

    Return _Buffer
End Function

我使用此功能将文件 ("C:\sample.xlsx") 保存到数据库(我使用 Microsoft SQL 服务器)作为 SqlDbType.Image

下面是我用来从数据库中获取值并尝试再次将其转换为文件的代码。

Dim FileInBinary() As Byte
Dim CurrentRS As Recordset

'Select
SQLString = "SELECT FileInBinary from table where ID=1"

'Get value to a recordSet
CurrentRS = ServerRunSQL_Return(SQLString)

'SaveValue to Dim
FileInBinary = CurrentRS.Fields(0).Value

'Try to convert
My.Computer.FileSystem.WriteAllBytes("C:\sample_new.xlsx", FileInBinary, True)

我也试过:

File.WriteAllBytes("C:\sample_new.xlsx", FileInBinary)

如何 select 这个值并将其再次转换为文件 ("C:\sample_new.xlsx")?

将函数 FileToByteArray 替换为 File.ReadAllBytes("C:\sample.xlsx")

下面是从数据库中获取值并将其再次转换为文件的代码。

Dim FileInbinary As Byte()
SqlConn.Open()
Dim command As New SqlCommand("SELECT FileInBinary from table where ID=1", SqlConn) 
FileInbinary = DirectCast(command.ExecuteScalar(), Byte())
SqlConn.Close()
File.WriteAllBytes("C:\sample_new.xlsx", FileInbinary)