Visual Basic Code Snippet - Object to byte array
(VB) Visual Basic code snippet convert object to byte array. This method useful to store binary data in files. This function can be use to convert any object to byte array and store them in database.
Bookmark:
Visual Basic Code Snippet - Object to byte array
This .Net Visual Basic code snippet convert object to byte array. This method useful to store binary data in files. Most common method to store binary data in database is as a byte array format. This function can be use to convert any object to byte array and store them in database. This function uses System.IO and System.Runtime.Serialization.Formatters.Binary name spaces to convert object to byte array. Modify the exception handling section as to your project requirements.
Data that is serialized is easy to represent, transport, and store. Serialized data is naturally represented by byte arrays. Byte arrays, accordingly, are very easy to manipulate programmatically. Transmitting a Byte array over network is straightforward; indeed, a send() call on a standard socket requires a Byte array as a parameter. Additionally, serialized data can then be stored. It is intuitive that storing a Byte array onto some type of disk storage is straightforward, since fundamentally these devices deal with sequences of bytes.
''' <summary>
''' Function to get byte array from a object
''' </summary>
''' <param name="_Object">object to get byte array</param>
''' <returns>Byte Array</returns>
Public Function ObjectToByteArray(ByVal _Object As Object) As Byte()
Try
' create new memory stream
Dim _MemoryStream As New System.IO.MemoryStream()
' create new BinaryFormatter
Dim _BinaryFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
' Serializes an object, or graph of connected objects, to the given stream.
_BinaryFormatter.Serialize(_MemoryStream, _Object)
' convert stream to byte array and return
Return _MemoryStream.ToArray()
Catch _Exception As Exception
' Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
End Try
' Error occured, return null
Return Nothing
End Function
Here is a simple example showing how to use above function (ObjectToByteArray). In this example we convert picturebox image object to byte array.
Dim _ByteArray() As Byte = ObjectToByteArray(pictureBox1.Image)
VB Keywords Used:
- MemoryStream
- BinaryFormatter
- Serialize
- byte
- Exception
Code Snippet Information:
- Applies To: Visual Studio, .Net, VB, Visual Basic, CLI, Byte Array, Object to byte array, Binary Data, Serialization, BinaryFormatter, Store binary data in database
- Programming Language : Visual Basic (VB)
External Resources:
yves :: May 20-2010 :: 03:53 PM
Help a bit DotNet and add
_MemoryStream.Close() before leaving the Function.