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:
<code class="language-csharp">[Serializable] public class MyClass { public string MyProperty { get; set; } } MyClass myObject = new MyClass { MyProperty = "myValue" };</code>
Saving myObject
to a file can be done using these methods:
Binary Serialization:
<code class="language-csharp">WriteToBinaryFile<MyClass>("C:\myObject.bin", myObject);</code>
XML Serialization:
<code class="language-csharp">WriteToXmlFile<MyClass>("C:\myObject.xml", myObject);</code>
JSON Serialization:
<code class="language-csharp">WriteToJsonFile<MyClass>("C:\myObject.json", myObject);</code>
These functions accept a file path and the object to serialize.
To retrieve the object:
Binary Serialization:
<code class="language-csharp">MyClass myObject = ReadFromBinaryFile<MyClass>("C:\myObject.bin");</code>
XML Serialization:
<code class="language-csharp">MyClass myObject = ReadFromXmlFile<MyClass>("C:\myObject.xml");</code>
JSON Serialization:
<code class="language-csharp">MyClass myObject = ReadFromJsonFile<MyClass>("C:\myObject.json");</code>
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!