///
/// Serializer class. Load and Save classes from/to XML files.
///
public class XSerial
{
///
/// Load a class from a serialized XML file.
///
/// full path or path relative to the XML file
/// type of the class that is being retrieved (Use typeof(ClassName))
/// A populated version of the class, or null on failure
/// Can throw several exceptions for IO and serialization loading
public static T Load(string filename)
{
T ob = default(T);
using (Stream s = File.Open(filename, FileMode.Open))
{
StreamReader sr = new StreamReader(s);
ob = DeserializeObject(sr.ReadToEnd());
s.Close();
}
return ob;
}
///
/// Save an instance of a class to an XML file
///
/// Full or relative path to the file
/// Class to serialize and save.
/// Type of the class (use: typeof(ClassName)
/// True on success, False on failure
public static void Save(string filename, T cls)
{
using (Stream s = File.Open(filename, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write( SerializeObject(cls) );
sw.Close();
s.Close();
return;
}
}
}
///
/// Serialize the object into an XML format
///
/// Type of object to serialize
/// the object to serialize
/// a string representing the XML version of the object
public static String SerializeObject(T pObject)
{
MemoryStream memoryStream = new MemoryStream();
UTF8Encoding encoding = new UTF8Encoding();
XmlSerializer xs = new XmlSerializer(typeof(T));
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, (object) pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
return encoding.GetString(memoryStream.ToArray());
}
///
/// Deserialize the object back into the object from an XML string
///
/// Type of the object to restore
/// The string that represents the object in XML
/// A new instance of the restored object
public static T DeserializeObject(String pXmlizedString)
{
UTF8Encoding encoding = new UTF8Encoding();
XmlSerializer xs = new XmlSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(pXmlizedString));
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.UTF8);
return (T)xs.Deserialize(memoryStream);
}
}
}