C# Code Snippet - Byte array to object

C# Code Snippet - Byte array to object

C# Code Snippet - Byte array to object

(C-Sharp) C# code snippet convert byte array to object. This function useful to convert back byte array data to its original object representation. This function can be use to deserialize those byte array data (Serialized) to their original objects.

Bookmark:

C# Code Snippet - Byte array to object

This .Net C# code snippet convert byte array to object. This function useful to convert back byte array data to its original object representation. Most common method to store binary data in database is as a byte array format. This function can be use to deserialize those byte array data (Serialized) to their original objects like image data ..etc. This function uses System.IO and System.Runtime.Serialization.Formatters.Binary name spaces to convert byte array to object. Modify the exception handling section as to your project requirements.

Note that it will be necessary to cast the returned generic Object from the deserialization method back into the original type of object you passed in to the serialization method originally.

/// <summary>
/// Function to get object from byte array
/// </summary>
/// <param name="_ByteArray">byte array to get object</param>
/// <returns>object</returns>
public object ByteArrayToObject(byte[] _ByteArray)
{
    try
    {
        // convert byte array to memory stream
        System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);

        // create new BinaryFormatter
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter 
                    = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        // set memory stream position to starting point
        _MemoryStream.Position = 0;

        // Deserializes a stream into an object graph and return as a object.
        return _BinaryFormatter.Deserialize(_MemoryStream);
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    // Error occured, return null
    return null;
}


Here is a simple example showing how to use above function (ByteArrayToObject). In this example we convert byte array variable (_ByteArray) to image and show the image in picturebox.

byte[] _ByteArray = .... some data ....;

pictureBox1.Image = (Image)ByteArrayToObject(_ByteArray);


C# Keywords Used:

  • MemoryStream
  • BinaryFormatter
  • Deserialize
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, Byte Array, Byte array to object, Binary Data, Deserialize, BinaryFormatter, Store binary data in database
  • Programming Language : C# (C-Sharp)

External Resources:

The End :: November 26-2010 :: 07:10 AM

Good! But, where is the filename to open for deserialize and show it on pictureBox1?Please!

Leave a comment