How to quickly save/load class instance to file

后端 未结 7 1429
终归单人心
终归单人心 2020-12-09 05:33

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         


        
相关标签:
7条回答
  • 2020-12-09 06:12

    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);
    }
    
    0 讨论(0)
提交回复
热议问题