Converting a .net Object to a Byte Array and Back

Converting a .net Object to a Byte Array and Back

No Comments on Converting a .net Object to a Byte Array and Back

To convert an object into a byte array and back to an object is quite simple. There are a few ways to do this, one way is to use a MemoryStream and BinaryFormatter to serialize the object into a byte array. The process in converting the byte array back into an object is quite similar, the MemoryStream is initialized with the byte array as a parameter and the formatter uses the Deserialize method.

Example:

namespace MPSHouse.Tools
{
    public class mpsh_ByteArray
    {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        /// <summary>
        /// Convert a .net object to a byte array.
        /// </summary>
        /// <param name="obj">
        /// Object to convert to a byte array.
        /// </param>
        /// <returns>A byte array.</returns>
        public byte[] ObjectToByteArray(Object obj)
        {
            MemoryStream fs = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, obj);
            byte[] rval = fs.ToArray();
            fs.Close();
            return rval;
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        /// <summary>
        /// Convert a byte array to a .net object.
        /// </summary>
        /// <param name="Buffer">
        /// The byte array to convert to a .net object.
        /// </param>
        /// <returns>A .net object.</returns>
        public object ByteArrayToObject(Byte[] Buffer)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(Buffer);
            object rval = formatter.Deserialize(stream);
            stream.Close();
            return rval;
        }
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    }

About the author:

Bill Payne started working as a paid professional software developer at the young age of 12 years old developing simple games and other applications for pre-packaged computers. Bill has since developed software for many industries such as direct sales and the the stock market. Bill has now started sharing his many years of software development experience through a blog on the MPSHouse website and one on one lessons.

Leave a comment

Back to Top