Serializing allows you to simply store or load an object’s contents to a XML file.
Classes can be serialized to XML. All public fields will be serialized automatically
Use the [XmlIgnoreAttribute] to prevent serialization.
Example
[XmlIgnoreAttribute]
int notToBeSerialized;
Sample:
Save or load an object to an XML file.
These functions can throw exceptions which must be handled !
class XMLSerializer
{
public static T read<T>(string path)
{
T data = default(T);
System.IO.TextReader reader = new System.IO.StreamReader(path);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
data = (T)ser.Deserialize(reader);
reader.Close();
reader.Dispose();
return (data);
}
public static void write<T>(string path, string filename, T data)
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
path += "\" + filename;
System.IO.TextWriter writer = new System.IO.StreamWriter(path);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
ser.Serialize(writer, data);
writer.Close();
writer.Dispose();
return (true);
}
}