Persisting and Restoring Objects in Files using C#
Object serialization enables the storage and retrieval of an object's state. This requires the object's class to be marked with the [Serializable]
attribute.
Let's illustrate with an example:
[Serializable] public class MyClass { public string MyProperty { get; set; } } MyClass myObject = new MyClass { MyProperty = "myValue" };
Saving myObject
to a file can be done using these methods:
Binary Serialization:
WriteToBinaryFile<MyClass>("C:\myObject.bin", myObject);
XML Serialization:
WriteToXmlFile<MyClass>("C:\myObject.xml", myObject);
JSON Serialization:
WriteToJsonFile<MyClass>("C:\myObject.json", myObject);
These functions accept a file path and the object to serialize.
To retrieve the object:
Binary Serialization:
MyClass myObject = ReadFromBinaryFile<MyClass>("C:\myObject.bin");
XML Serialization:
MyClass myObject = ReadFromXmlFile<MyClass>("C:\myObject.xml");
JSON Serialization:
MyClass myObject = ReadFromJsonFile<MyClass>("C:\myObject.json");
These functions use the file path and return the deserialized object.
Crucially, the class must have the [Serializable]
attribute for serialization and deserialization to work correctly.
The above is the detailed content of How Can I Save and Retrieve Serialized Objects in Files Using C#?. For more information, please follow other related articles on the PHP Chinese website!