0

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");
  • “…throws the exception” — **what** exception? – Ondrej Tucny Sep 01 '16 at 19:48
  • "Exception: Thrown: "Could not load file or assembly 'Memento test.XmlSerializers, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null' or one of its dependencies. Cannot find the file specified." (System.IO.FileNotFoundException) A System.IO.FileNotFoundException was thrown: "Could not load file or assembly 'Memento test.XmlSerializers, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null' or one of its dependencies. Cannot find the file specified." Time: 2016-09-01 10:04:51 p.m. Thread: [5204]" – baumeister Sep 01 '16 at 20:07
  • You can safely ignore that. This is normal behavior. – Ondrej Tucny Sep 01 '16 at 20:17
  • @baumeister - the *first* exception you are seeing is not relevant. It will be caught and ignored internally, and then you will get the "real" exception, `System.InvalidOperationException: Memento cannot be serialized because it does not have a parameterless constructor.` To serialize your class with `XmlSerializer` you must have such a constructor. See [here](https://stackoverflow.com/questions/267724). – dbc Sep 01 '16 at 20:32
  • 1
    It's works now, with parametless constructor. Also "Memento" properties have to have public setters. Thank you for your help :) – baumeister Sep 01 '16 at 20:46

0 Answers0