Visual Basic Code Snippet - Convert file to byte array

Visual Basic Code Snippet - Convert file to byte array

Visual Basic Code Snippet - Convert file to byte array

(VB) Visual Basic code snippet convert external file to byte array. Converting file into byte array important to store binary file in database, send to other systems using remoting.

Bookmark:

Visual Basic Code Snippet - Convert file to byte array

This .Net Visual Basic code snippet convert external file to byte array. Converting file into byte array important to store binary file in database, send to other systems using remoting. To use this function simply provide file path to external file. This function uses System.IO name space to open file using FileStream and reading from BinaryReader. Modify the exception handling section to as your project requirements.

''' <summary>
''' Function to get byte array from a file
''' </summary>
''' <param name="_FileName">File name to get byte array</param>
''' <returns>Byte Array</returns>
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


Here is a simple example showing how to use above function (FileToByteArray) load external image in a file to byte array and show it in a picturebox (this is just to demonstrate this function, there are other methods to load image in picturebox).

Dim _MemoryStream As New System.IO.MemoryStream(FileToByteArray("C:\sample-image.jpg"))
pictureBox1.Image = System.Drawing.Image.FromStream(_MemoryStream)


Here is a simple example showing how to use above function (FileToByteArray) to store image in sql server database. This example shows how to read external file and convert it into byte array and then insert binary data into SQL server as a new record using sql parameter.

' set temporary variable for database connection
Dim _SqlConnection As New System.Data.SqlClient.SqlConnection()

' assign database connection string
_SqlConnection.ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;"

' Connect to database
Try
    ' open database connection
    _SqlConnection.Open()

    ' Set SQL statement to insert new record to database
    Dim _SQL As String = "INSERT INTO sampletable (name, price, image) VALUES ('sample product name', 22.75, @image)"

    ' lets add this record to database
    Dim _SqlCommand As New System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection)

    ' Add image as SQL parameter
    Dim _SqlParameter As New System.Data.SqlClient.SqlParameter("@image", SqlDbType.Image)

    ' convert image file to byte array and pass to sql parameter value
    _SqlParameter.Value = FileToByteArray("C:\sample-image.jpg")
    _SqlCommand.Parameters.Add(_SqlParameter)

    ' Executes a Transact-SQL statement against the connection 
    _SqlCommand.ExecuteNonQuery()

    ' Dispose command
    _SqlCommand.Dispose()
    _SqlCommand = Nothing

Catch _Exception As Exception
    ' Error
    Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
End Try

' close database connection
_SqlConnection.Close()


VB Keywords Used:

  • FileStream
  • BinaryReader
  • FileInfo
  • FileMode
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, VB, Visual Basic, CLI, SQL, FileStream, BinaryReader, FileMode, File to byte array, Remoting, Store binary in database, SQL Server Binary Data
  • Programming Language : Visual Basic (VB)

External Resources:

Leave a comment