Visual Basic Code Snippet - Save byte array to file
(VB) Visual Basic code snippet save byte array in to an external file. This function useful to store binary data in files. This function can be use when retrieving binary data from database and save it to an external file.
Bookmark:
Visual Basic Code Snippet - Save byte array to file
This .Net Visual Basic code snippet save byte array in to an external file. This function useful to store binary data in files. Function return true if byte array successfully written to file, else return false. Most common method to store binary data in database is as a byte array format. This function can be use when retrieving binary data from database and save it to an 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 save byte array to a file ''' </summary> ''' <param name="_FileName">File name to save byte array</param> ''' <param name="_ByteArray">Byte array to save to external file</param> ''' <returns>Return true if byte array save successfully, if not return false</returns> Public Function ByteArrayToFile(ByVal _FileName As String, ByVal _ByteArray() As Byte) As Boolean Try ' Open file for reading Dim _FileStream As New System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write) ' Writes a block of bytes to this stream using data from a byte array. _FileStream.Write(_ByteArray, 0, _ByteArray.Length) ' close file stream _FileStream.Close() Return True Catch _Exception As Exception ' Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()) End Try ' error occured, return false Return False End Function
Here is a simple example showing how to use above function (ByteArrayToFile). In this example we save byte array variable _ByteArray into a file byte-array.dat.
Dim _ByteArray() As Byte = ..... some data ..... ByteArrayToFile("c:\image-object.dat", _ByteArray)
VB Keywords Used:
- FileStream
- FileAccess
- FileMode
- byte
- Exception
Code Snippet Information:
- Applies To: Visual Studio, .Net, VB, Visual Basic, CLI, SQL, Byte array to file, FileMode, FileAccess
- Programming Language : Visual Basic (VB)
External Resources: