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:
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false) public static T ReadFromBinaryFile<T>(string filePath)
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()
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()
Save the contents of the object1
variable to a file using binary serialization:
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
Read the file contents back into a variable:
SomeClass object1 = ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
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!