Search code examples
c#.netfileserialization

How to quickly save/load class instance to file


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 someothervalue
}

And my collection

List<A> _myList;

I need to be able to save _myList and load. I just want to save all class fields to file and load. I don't want to spend time writing my own save/load. Are there any tools in .NET to help me. I don't care about the file format.


Solution

  • XMLSerializer isn't hard to use. As long as your objects aren't huge, it's pretty quick. I serialize out some huge objects in a few of my apps. It takes forever and the resulting files are almost 100 megs, but they're editable should I need to tweak some stuff. Plus it doesn't matter if I add fields to my objects. The serialized files of the older version of the object still deserialize properly.. I do the serialization on a separate thread so it doesn't matter how long it takes in my case. The caveat is that your A class has to have a constructor for XMLSerialziation to work.

    Here's some working code I use to serialize/deserialize with the error handling ripped out for readibility...

    private List<A> Load()
    {
        string file = "filepath";
        List<A> listofa = new List<A>();
        XmlSerializer formatter = new XmlSerializer(A.GetType());
        FileStream aFile = new FileStream(file, FileMode.Open);
        byte[] buffer = new byte[aFile.Length];
        aFile.Read(buffer, 0, (int)aFile.Length);
        MemoryStream stream = new MemoryStream(buffer);
        return (List<A>)formatter.Deserialize(stream);
    }
    
    
    private void Save(List<A> listofa)
    {
        string path = "filepath";
        FileStream outFile = File.Create(path);
        XmlSerializer formatter = new XmlSerializer(A.GetType());
        formatter.Serialize(outFile, listofa);
    }