Home >Backend Development >C++ >How to Serialize and Deserialize Objects to/from Files in C#?

How to Serialize and Deserialize Objects to/from Files in C#?

DDD
DDDOriginal
2025-01-23 11:51:10979browse

How to Serialize and Deserialize Objects to/from Files in C#?

C# Object File Saving and Restoration

Saving the object to the computer requires that the object be serializable. This means that the object must be able to be converted into a format that can be written to a file, and then later read back into memory and converted back into an object. The following functions perform serialization and deserialization:

Binary serialization

<code class="language-csharp">public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
public static T ReadFromBinaryFile<T>(string filePath)</code>

XML serialization

<code class="language-csharp">public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
public static T ReadFromXmlFile<T>(string filePath) where T : new()</code>

JSON serialization

<code class="language-csharp">public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
public static T ReadFromJsonFile<T>(string filePath) where T : new()</code>

Example

Save the contents of the object1 variable to a file using binary serialization:

<code class="language-csharp">WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);</code>

Read the file contents back into a variable:

<code class="language-csharp">SomeClass object1 = ReadFromBinaryFile<SomeClass>("C:\someClass.txt");</code>

The above is the detailed content of How to Serialize and Deserialize Objects to/from Files in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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