[Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", Name); info.AddValue("Age", Age); } protected Person(SerializationInfo info, StreamingContext context) { Name = info.GetString("Name"); Age = info.GetInt32("Age"); } }
public static void SerializeToXmlFileIn this example, two static utility methods are defined for serialization and deserialization of objects to/from XML files. Both methods use the XmlSerializer class, which is part of the System.Xml.Serialization namespace. The SerializeToXmlFile() method takes two arguments: a file path and an object to serialize. It creates a new instance of the XmlSerializer class and uses it to serialize the object to the specified file path. The DeserializeFromXmlFile() method takes a single argument: a file path from which to deserialize an object. It creates a new instance of the XmlSerializer class and uses it to deserialize the object from the specified file path. The System.Runtime.Serialization namespace is part of the .NET Framework Class Library, which is included in the .NET runtime package.(string filePath, T obj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StreamWriter writer = new StreamWriter(filePath)) { serializer.Serialize(writer, obj); } } public static T DeserializeFromXmlFile (string filePath) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StreamReader reader = new StreamReader(filePath)) { return (T)serializer.Deserialize(reader); } }