Home > Backend Development > C++ > How Can I Save and Retrieve Serialized Objects in Files Using C#?

How Can I Save and Retrieve Serialized Objects in Files Using C#?

Mary-Kate Olsen
Release: 2025-01-23 11:31:14
Original
159 people have browsed it

How Can I Save and Retrieve Serialized Objects in Files Using C#?

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>
Copy after login

Saving myObject to a file can be done using these methods:

Binary Serialization:

<code class="language-csharp">WriteToBinaryFile<MyClass>("C:\myObject.bin", myObject);</code>
Copy after login

XML Serialization:

<code class="language-csharp">WriteToXmlFile<MyClass>("C:\myObject.xml", myObject);</code>
Copy after login

JSON Serialization:

<code class="language-csharp">WriteToJsonFile<MyClass>("C:\myObject.json", myObject);</code>
Copy after login

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>
Copy after login

XML Serialization:

<code class="language-csharp">MyClass myObject = ReadFromXmlFile<MyClass>("C:\myObject.xml");</code>
Copy after login

JSON Serialization:

<code class="language-csharp">MyClass myObject = ReadFromJsonFile<MyClass>("C:\myObject.json");</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template