I have several collections of classes/structs in my app.
The class is just a class with fields
class A
{
public int somevalue;
public string some
Old topic, but I modified Tim Coker's answer above to utilize the using blocks to properly dispose of the stream objects and save only a single class instance at a time:
public static T Load(string FileSpec) {
XmlSerializer formatter = new XmlSerializer(typeof(T));
using (FileStream aFile = new FileStream(FileSpec, FileMode.Open)) {
byte[] buffer = new byte[aFile.Length];
aFile.Read(buffer, 0, (int)aFile.Length);
using (MemoryStream stream = new MemoryStream(buffer)) {
return (T)formatter.Deserialize(stream);
}
}
}
public static void Save(T ToSerialize, string FileSpec) {
Directory.CreateDirectory(FileSpec.Substring(0, FileSpec.LastIndexOf('\\')));
FileStream outFile = File.Create(FileSpec);
XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter.Serialize(outFile, ToSerialize);
}