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
public static class BinarySerializerHelper
Constants
#region Constants
private const string FILE_EXTENSION = ".dat";
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
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
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"));
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
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
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
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.