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
1031 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

public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
public static T ReadFromBinaryFile<T>(string filePath)
Copy after login

XML serialization

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

JSON serialization

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

Example

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

WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
Copy after login

Read the file contents back into a variable:

SomeClass object1 = ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
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!

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