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:
<code class="language-csharp">public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false) public static T ReadFromBinaryFile<T>(string filePath)</code>
<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>
<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>
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!