Object serialization using BinaryFormatter

Typically, when serializing objects, JSON is preferred. However, on a project I’m working on, I’m sending objects to RabbitMQ, which uses byte arrays. Basically, I’m storing the contents of files on a queue to be processed by another application.

[Serializable]
public class Layout
{
    public string Filename { get; set; }
    public string Mode { get; set; }
    public byte[] Contents { get; set; }
}
class Program
{
    const string _filename = @"d:\Vengeance - Zack Hemsey.wav";
    const string _action = "Create";
    static void Main(string[] args)
    {
        Layout layout = new Layout
        {
            Filename = _filename,
            Mode = _action,
            Contents = File.ReadAllBytes(_filename)
        };
        
        using (MemoryStream mTest = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(mTest, layout);
            mTest.Position = 0;
            byte[] bytes = mTest.ToArray();
            Layout fromByteArray = ByteArrayToObject<Layout>(bytes);
            Layout deserializedLayout = (Layout)binaryFormatter.Deserialize(mTest);
        }
        Console.WriteLine("Serialization/deserialization complete");
    }

    public static T ByteArrayToObject<T>(byte[] arrBytes)
    {
        using (var memStream = new MemoryStream())
        {
            var binForm = new BinaryFormatter();
            memStream.Write(arrBytes, 0, arrBytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            object obj = binForm.Deserialize(memStream);
            return (T)obj;
        }
    }
}

About the Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You may also like these