Click here to Skip to main content
Licence CPOL
First Posted 11 May 2008
Views 8,979
Downloads 79
Bookmarked 14 times

Binary Serializer Helper Class

By | 11 May 2008 | Article
Class to serialize/deserialize objects from/to bytes or files.

Introduction

This is a helper class to serialize/deserialize objects from/to bytes or files. This class encapsulates the BinaryFormatter for both operations.

Although the binary formatter usage is straightforward and it only requires couple lines of code, I think it's annoying to keep repeating the same lines on each piece that requires this functionality, and that's why I created a class to encapsulate such lines, and with only one line of code you will get your expected results.

Note: This is not a fancy or advanced class, it just helps you to write one line of code instead of 3-4 lines; I use it all the time, so I thought you guys might benefit from it the same way I do.

Using the code

As it's obvious for you now, this class should be static as its a helper class. And, no properties are to be set, and there is no need to create an instance each time you want to call a method.

Class definition

/// <author>Yazeed Hamdan</author>
/// <summary>
/// Serialize/Deserialize any object from/to any file or serialize/Deserialize it
/// into/From bytes array
/// </summary>
public static class BinarySerializerHelper

Constants

#region Constants
/// <summary>
/// Default Binary File Extension 
/// </summary>
private const string FILE_EXTENSION = ".dat";
/// <summary>
/// Category for Exceptions thrown
/// </summary>
private const string CATEGORY = "BinarySerializerHelper::{0}";
#endregion
  • FILE_EXTENSION: When serializing to a file, the extension will be set to *.dat.
  • CATEGORY: For exception management and logging purposes which is defined in each exception thrown.

Note: this class is not integrated with any logging or exception management handlers.

Members

#region Members
/// <summary>
/// Singleton object of BinaryFormatter
/// </summary>
private static BinaryFormatter _formatter = new BinaryFormatter(); 
#endregion

Only one member is defined, which is the BinaryFormatter. No need to keep creating the formatter in each method, just create it once during the process and it will be used by all the methods in this class.

Methods

Serialization

/// <summary>
/// Serialize Any object to a file
/// </summary>
/// <param name="currentObject"><see cref="System.Object"/></param>
/// <param name="filename">file name and where this file will be saved</param>
/// <remarks>The application should have enough permissions to
/// access/create a file on the targeted machine</remarks>
public static void Serialize(object currentObject, string filename)
{
    if(null == currentObject)
        throw new ArgumentNullException(string.Format(
            CATEGORY, "Serialize, Passed Object to Serialize Is Null"));
    if(string.IsNullOrEmpty(filename))
        throw new ArgumentNullException(string.Format(
            CATEGORY, "Serialize,Cannot Serialize object, Filename Is Null"));
                
    //Append File Extension
    filename += FILE_EXTENSION;
    using(Stream fileStream = new FileStream(filename, FileMode.Create))
        _formatter.Serialize(fileStream, currentObject);
}

This method will serialize any object to a binary file; you just specify the file name (fully qualified with the path) and your object, the file will be saved as *.dat.

Another overload for the Serialize method

/// <summary>
/// Serialize any object to a bytes array
/// </summary>
/// <param name="currentObject"><see cref="System.Object"/></param>
/// <returns><see cref="System.Byte"/></returns>
public static byte[] Serialize(object currentObject)
{
    if(null == currentObject)
        throw new ArgumentNullException(string.Format(
            CATEGORY, "Serialize, Object to Serialize Is Null"));
    byte[] binaryData = null;
    
    using(Stream memoryStream = new MemoryStream())            
    {
        _formatter.Serialize(memoryStream, currentObject);        
        memoryStream.Position = 0;
        binaryData = new byte[memoryStream.Length];
        memoryStream.Read(binaryData, 0, Convert.ToInt32(memoryStream.Length));
    }
    return binaryData;
}

This overload takes your object and serializes it to a byte[].

Deserialization

/// <summary>
/// Deserialize any binary data to an object from a file 
/// </summary>
/// <param name="filename">where the binary data is located</param>
/// <returns><see cref="System.Object"/></returns>
/// <remarks>Client should be aware of the object type</remarks>
public static object Deserialize(string filename)
{
    if(string.IsNullOrEmpty(filename))
        throw new ArgumentNullException(string.Format(
            CATEGORY, "Deserialize, Filename Is Null"));
    object deserializedObject = null;
    using(Stream fileStream = File.OpenRead(filename))
        deserializedObject = _formatter.Deserialize(fileStream);
    return deserializedObject;
}

When deserializing a binary file to an object, you should be aware of the binary file data and the current object which such data is deserialized against, as you should do the casting for the returned object. As an enhancement, you can add a Generic type to this method to do the type casting for you.

Another overload for the Deserialize method

/// <summary>
/// Deserialize any binary data to an object from a bytes array 
/// </summary>
/// <returns><see cref="System.byte"/></returns>
/// <remarks>Client should be aware of the object type</remarks>
public static object Deserialize(byte[] binaryData)
{
    if(null == binaryData || binaryData.Length == 0)
        throw new ArgumentNullException(string.Format(
            CATEGORY, "Deserialize, binaryData Is Null or Empty"));
    object deserializedObject = null;
    using(Stream memoryStream = new MemoryStream())
    {                                                
        memoryStream.Write(binaryData, 0, binaryData.Length);
        memoryStream.Position = 0;
        deserializedObject = _formatter.Deserialize(memoryStream);
    }
    return deserializedObject;
}

This method will deserialize a byte[] array to an object. As I said earlier, you can add a Generic type to this method to do the casting.

Conclusion

This class is only a helper one, nothing fancy in it. It just encapsulates the code needed for using a BinaryFormatter to do the serialization/deserialization.

Hope you can benefit from it. Thank you all for reading.

History

Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Yazeed Hamdan

Architect

Jordan Jordan

Member

MCAD.NET, MCPD.NET

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralNot Important PinmemberRi Qen-Sin3:17 11 May '08  
GeneralRe: Not Important PinmemberYazeed Hamdan3:43 11 May '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 11 May 2008
Article Copyright 2008 by Yazeed Hamdan
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid