Introduction
I had previously published a tip (Serializing to a String[^]) on serializing objects to a string
because I had a need to save to an object to Settings
. Somebody commented that it would be more efficient to save a binary
, which is true, but I do not think you can save binary to a Settings
entry. This is a class that I would use if I had to save to a file. Can easily be changed to either XML or binary.
Potential Serializer Gotchas
There are a number of issues that you can run into when serializing, and the compiler does not seem to be much help and the error messages are not much either:
- Properties of classes to be serialized must be public
- All properties that are not marked to not be serialized must have both a setter and getter
- The class to be serialized must have a default constructor which is a constructor that takes no parameters
The Code
The class that does the serialization and deserialization to an XML file is two short static
methods in a static
class
:
public static bool SerializedToXmlFile<T>(T serializableObject, string fileName)
{
if (serializableObject.Equals(default(T))) return false;
try
{
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StreamWriter(fileName))
{
serializer.Serialize(writer, serializableObject);
writer.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public static T DeSerializeFromXmlFile<T>(string fileName)
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StreamReader(fileName))
return (T)serializer.Deserialize(reader);
}
catch (Exception ex)
{
return default(T);
}
}
The class
that does the serialization and deserialization to a binary file is also two short static
methods in a static
class
:
public static bool SerializedToBinaryFile<T>(T serializableObject, string fileName)
{
if (serializableObject.Equals(default(T))) return false;
try
{
var serializer = new BinaryFormatter();
using (var writer = File.Open(fileName, FileMode.Create))
{
serializer.Serialize(writer, serializableObject);
writer.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public static T DeSerializeFromBinaryFile<T>(string fileName)
{
try
{
var serializer = new BinaryFormatter();
using (var reader = File.Open(fileName, FileMode.Open, FileAccess.Read))
return (T)serializer.Deserialize(reader);
}
catch (Exception ex)
{
return default(T);
}
}
Saving an object to binary has two advantages compared to XML: smaller size, and very difficult for a user read. Of course saving in XML has the advantage of being able to look at the saved data and diagnose problems. Also, for real security, really need to encrypt the file to protect it.
There is really no error handling in these, and it may be desirable to put it in.
Summary
These methods makes it very easy to serialize an object to and from a file. It proves appropriate level of encapsulation when the file path is known, but probably is not appropriate if the user will be asked for the file