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
Release: 2025-01-23 11:51:10
Original
978 people have browsed it

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

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

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

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

Read the file contents back into a variable:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template