How to save/restore serializable object to/from file?

前端 未结 6 876
旧时难觅i
旧时难觅i 2020-11-22 11:17

I have a list of objects and I need to save that somewhere in my computer. I have read some forums and I know that the object has to be Serializable. But it wou

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 11:52

    You'll need to serialize to something: that is, pick binary, or xml (for default serializers) or write custom serialization code to serialize to some other text form.

    Once you've picked that, your serialization will (normally) call a Stream that is writing to some kind of file.

    So, with your code, if I were using XML Serialization:

    var path = @"C:\Test\myserializationtest.xml";
    using(FileStream fs = new FileStream(path, FileMode.Create))
    {
        XmlSerializer xSer = new XmlSerializer(typeof(SomeClass));
    
        xSer.Serialize(fs, serializableObject);
    }
    

    Then, to deserialize:

    using(FileStream fs = new FileStream(path, FileMode.Open)) //double check that...
    {
        XmlSerializer _xSer = new XmlSerializer(typeof(SomeClass));
    
        var myObject = _xSer.Deserialize(fs);
    }
    

    NOTE: This code hasn't been compiled, let alone run- there may be some errors. Also, this assumes completely out-of-the-box serialization/deserialization. If you need custom behavior, you'll need to do additional work.

提交回复
热议问题