I have the following xml file:
<MyConfig>
<Item a1="Attrib11" a2="Attrib21" a3="Attrib31" />
<Item a1="Attrib12" a2="Attrib22" a3="Attrib32" />
</MyConfig>
I load it in using the following helper methods:
public static T Load<T>(string path)
{
XmlSerializer xml = new XmlSerializer(typeof(T));
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader sr = new StreamReader(fs))
{
return (T)xml.Deserialize(sr);
}
}
public static void Save<T>(string path, T contents)
{
XmlSerializer xml = new XmlSerializer(typeof(T));
using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
using (StreamWriter sw = new StreamWriter(fs))
{
xml.Serialize(sw, contents, ns);
}
}
This is MyConfig
:
public class MyConfig
{
[XmlElement("Item")]
public List<Item> Items { get; set; }
public MyConfig()
{
Items = new List<Item>();
}
}
public class Item : IXmlSerializable
{
[XmlAttribute()]
public string Attrib1 { get; set; }
[XmlAttribute()]
public string Attrib2 { get; set; }
[XmlAttribute()]
public string Attrib3 { get; set; }
public Item(string attrib1, string attrib2, string attrib3)
{
Attrib1 = attrib1;
Attrib2 = attrib2;
Attrib3 = attrib3;
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
if (reader.MoveToContent() == XmlNodeType.Element)
{
Attrib1 = reader.GetAttribute("a1");
Attrib2 = reader.GetAttribute("a2");
Attrib3 = reader.GetAttribute("a3");
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("a1", Attrib1);
writer.WriteAttributeString("a2", Attrib2);
writer.WriteAttributeString("a3", Attrib3);
}
}
I then have the following test bed code for checking the serialization of the class:
string file = "somePath";
MyConfig myConfig = new MyConfig()
{
Items = new List<Item>()
{
new Item("Attrib11", "Attrib21", "Attrib31"),
new Item("Attrib12", "Attrib22", "Attrib32"),
},
};
Save(file, myConfig);
MyConfig myConfig2 = Load<MyConfig>(file);
This fails with an OutOfMemory exception at Load
, how can I fix this? Checking the file at somePath
and it looks correct.