.NET/C# XML Serialization: Generic Helper for Loading/Saving

Helper Class

public abstract class XmlSerializationHelper
{
  public static T Load<T>(string fileName)
  {
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    TextReader reader = new StreamReader(fileName);
    T obj = (T)serializer.Deserialize(reader);
    reader.Close();
    return obj;
  }
 
  public static void Save<T>(T obj, string fileName)
  {
    TextWriter writer = new StreamWriter(fileName);
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(writer, obj);
    writer.Close();
  }
}

Example

public class Car
{
  public string Make { get; set; }
  public string Model { get; set; }
  public int DoorCount { get; set; }
}
 
public class Program
{
  static void Main(string[] args)
  {
    Car myCar = new Car()
    {
      DoorCount = 3,
      Make = "Peugeot",
      Model = "406"
    };
    XmlSerializationHelper.Save(myCar, "myCar.xml");
 
    Car myXmlCar = XmlSerializationHelper.Load("myCar.xml");
  }
}

XML Output

<?xml version="1.0" encoding="utf-8"?>
<Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Make>Peugeot</Make>
 <Model>406</Model>
 <DoorCount>3</DoorCount>
</Car>