Wednesday, April 25, 2012

Serialization Helper Methods

I keep forgetting the classes/methods I need to Serialize/Deserialize objects to and from XML. So I decided to make a couple of helper methods.


/// <summary>
/// Writes the serialized form of the object, in xml format, to the file
/// location specified.
/// </summary>
/// <typeparam name="T">type to serialize from</typeparam>
/// <param name="toSerialize">data to serialize</param>
/// <param name="fileLocation">to serialize the data too</param>
public static void Serialize<T>(T toSerialize, string fileLocation)
{
    if (toSerialize == null)
        throw new ArgumentException("The data to serialize cannot be null.");

    if (string.IsNullOrEmpty(fileLocation))
        throw new ArgumentException("You must provide a file location to output the data to.");

    using (var textWriter = new StreamWriter(fileLocation))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", ""); //turn off namespaces
        serializer.Serialize(textWriter, toSerialize, ns);
    }
}

/// <summary>
/// Reads the data from the file location specified and creates an instance
/// of the object type. The object must be serializable.
/// </summary>
/// <typeparam name="T">type to deserialize the data too</typeparam>
/// <param name="fileLocation">data to deserialize from</param>
/// <returns>new object of type T with properties filled out</returns>
public static T Deserialize<T>(string fileLocation)
{
    if (string.IsNullOrEmpty(fileLocation))
        throw new ArgumentException("You must provide a file location to read the data from.");

    using (var reader = XmlReader.Create(fileLocation))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(reader);
    }
}

They're pretty straight forward to use, but just for clarification.


public static void Main(string[] args)
{
    MyObject obj = Program.Deserialize<MyObject>(@"Files\SerializedData.xml");
    obj.AdjustValues();
    Console.WriteLine("Done!!!: {0} test: {1}", obj.Property1, obj.Property2);
    obj.AuditDirectoryName = "Test";
    Program.Serialize(obj, @"Files\SerializedData.xml");
    Console.ReadLine();
}

No comments:

Post a Comment