De- and Serialize XML

Published 3/13/2014 by Christian
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace baltz
{
    public class Utilities
    {
        /// <summary>
        /// Will read an XML file, containing an XML-serialized object of type 't', and return the deserialize object
        /// </summary>
        /// <param name="fileName">The full path of the file in question</param>
        /// <param name="t">The type of the object in the XML-serialized file (eg. this.GetType())</param>
        /// <exception cref="FileNotFoundException"></exception>
        /// <returns>An deserialize object of type 't'</returns>
        public object ReadXML(string fileName, Type t)
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException();
            }
            object xmlObject;
            using (FileStream reader = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                XmlSerializer serializer = new XmlSerializer(t);
                xmlObject = serializer.Deserialize(reader);
            }
            return xmlObject;
        }

        /// <summary>
        /// Will XML-serialize 'item' and write it to 'fileName'
        /// </summary>
        /// <param name="item">The object in question. Must be XML-serializeable, and declared as such</param>
        /// <param name="fileName">The full path of the file in question</param>
        public void WriteXML(object item, string fileName)
        {
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            XmlSerializer serializer = new XmlSerializer(item.GetType());

            using (TextWriter writer = new StreamWriter(fileName))
            {
                serializer.Serialize(writer, item);
            }
        }
    }
}