I'm trying to learn how to save an object to the file in c#. I'm trying to use Xml serialization and Memento pattern. The object that i want to save is of "caretaker" type. Here is how it looks like:
public class Memento
{
public int prop1 { get;private set; }
public String prop2 { get;private set; }
public int SomeClassProp { get; private set; }
public Memento(int p1, String p2, SomeClass sc)
{
this.prop1 = p1; this.prop2 = p2; this.SomeClassProp = sc.SomeClassProp1;
}
}
public class Caretaker
{
private Memento _memento;
// Gets or sets memento
public Memento Memento
{
set { _memento = value; }
get { return _memento; }
}
}
Serializer code (copied from stack overflow):
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
stream.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
}
/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }
T objectOut = default(T);
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
reader.Close();
}
read.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
return objectOut;
}
The problem lies here:
XmlSerializer(serializableObject.GetType());
Here is where it throws the exception, and in result the file is not created. I'm guessing there is something wrong with the type of object that I want to save, right? Can you anyone help me somehow?
Edit: Serializer usage:
c.Memento = this.CreateMemento();
SerializeObject<Caretaker>(c, "savedObj");