CHAPTER 20 FILE I/O AND OBJECT SERIALIZATION
{
}
}
// Rehydrate member variables from stream.
dataItemOne = si.GetString("First_Item").ToLower();
dataItemTwo = si.GetString("dataItemTwo").ToLower();
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext ctx)
{
// Fill up the SerializationInfo object with the formatted data.
info.AddValue("First_Item", dataItemOne.ToUpper());
info.AddValue("dataItemTwo", dataItemTwo.ToUpper());
}
Notice that when you fill the SerializationInfo type with the GetObjectData() method, you are not
required to name the data points identically to the type’s internal member variables. This can obviously
be helpful if you need to further decouple the type’s data from the persisted format. Be aware, however,
that you will need to obtain the values from the special, protected constructor using the same names
assigned within GetObjectData().
To test your customization, assume that you want to persist an instance of MyStringData using a
SoapFormatter (so update your assembly references and imports accordingly), as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Custom Serialization *****");
// Recall that this type implements ISerializable.
StringData myData = new StringData();
// Save to a local file in SOAP format.
SoapFormatter soapFormat = new SoapFormatter();
using(Stream fStream = new FileStream("MyData.soap",
FileMode.Create, FileAccess.Write, FileShare.None))
{
soapFormat.Serialize(fStream, myData);
}
Console.ReadLine();
}
When you view the resulting *.soap file, you will see that the string fields have been persisted in
uppercase, as so: