S3minaki
S3minaki

Reputation: 319

Convert From Byte[] to File

I use the following Function to convert a file to 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

I save the file ("C:\sample.xlsx") using this function to database(I use Microsoft SQL Server) as SqlDbType.Image

Below is the code that I use to get the value from db and try to convert it as a file again.

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)

I also tried:

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

How can I select this value and convert it again as file ("C:\sample_new.xlsx")?

Upvotes: 0

Views: 2334

Answers (1)

S3minaki
S3minaki

Reputation: 319

Replace the Function FileToByteArray with File.ReadAllBytes("C:\sample.xlsx")

Below is the code to get the value from db and convert it as a file again.

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)

Upvotes: 1

Related Questions