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.

01''' <summary>
02''' Function to get byte array from a file
03''' </summary>
04''' <param name="_FileName">File name to get byte array</param>
05''' <returns>Byte Array</returns>
06Public Function FileToByteArray(ByVal _FileName As String) As Byte()
07    Dim _Buffer() As Byte = Nothing
08 
09    Try
10        ' Open file for reading
11        Dim _FileStream As New System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
12 
13        ' attach filestream to binary reader
14        Dim _BinaryReader As New System.IO.BinaryReader(_FileStream)
15 
16        ' get total byte length of the file
17        Dim _TotalBytes As Long = New System.IO.FileInfo(_FileName).Length
18 
19        ' read entire file into buffer
20        _Buffer = _BinaryReader.ReadBytes(CInt(Fix(_TotalBytes)))
21 
22        ' close file reader
23        _FileStream.Close()
24        _FileStream.Dispose()
25        _BinaryReader.Close()
26    Catch _Exception As Exception
27        ' Error
28        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
29    End Try
30 
31    Return _Buffer
32End 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).

1Dim _MemoryStream As New System.IO.MemoryStream(FileToByteArray("C:\sample-image.jpg"))
2pictureBox1.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.

01' set temporary variable for database connection
02Dim _SqlConnection As New System.Data.SqlClient.SqlConnection()
03 
04' assign database connection string
05_SqlConnection.ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;"
06 
07' Connect to database
08Try
09    ' open database connection
10    _SqlConnection.Open()
11 
12    ' Set SQL statement to insert new record to database
13    Dim _SQL As String = "INSERT INTO sampletable (name, price, image) VALUES ('sample product name', 22.75, @image)"
14 
15    ' lets add this record to database
16    Dim _SqlCommand As New System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection)
17 
18    ' Add image as SQL parameter
19    Dim _SqlParameter As New System.Data.SqlClient.SqlParameter("@image", SqlDbType.Image)
20 
21    ' convert image file to byte array and pass to sql parameter value
22    _SqlParameter.Value = FileToByteArray("C:\sample-image.jpg")
23    _SqlCommand.Parameters.Add(_SqlParameter)
24 
25    ' Executes a Transact-SQL statement against the connection
26    _SqlCommand.ExecuteNonQuery()
27 
28    ' Dispose command
29    _SqlCommand.Dispose()
30    _SqlCommand = Nothing
31 
32Catch _Exception As Exception
33    ' Error
34    Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
35End Try
36 
37' close database connection
38_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

 Poster Information 


(will not be published, required)

 MESSAGE DETAILS