I try to use SurrogatSelector to customize the deserialisation of a stream. It works fine for the root object of the object graph but not for contained objects. See the following code:
Stream stream = File.Open("C:\\Temp\\test.bin", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
TestToSerialize tts = new TestToSerialize();
formatter.Serialize(stream, tts);
stream.Close();
stream = File.Open("C:\\Temp\\test.bin", FileMode.Open);
formatter = new BinaryFormatter();
SurrogateSelector ss = new SurrogateSelector();
ss.AddSurrogate(typeof(string), new StreamingContext(StreamingContextStates.All), new StringSerializationSurrogate());
formatter.SurrogateSelector = ss;
tts = (TestToSerialize)formatter.Deserialize(stream);
stream.Close();
The StringSerializationSurrogate gets called (method SetObjectData) when a string is deserialized, but not when an object containing a string (as a serilizable member) is deserialized. The object to be serialized/ deserialized looks like this:
[Serializable]
class TestToSerialize
{
public string s1;
public TestToSerialize()
{
s1 = "some test";
}
}
Is there a way to have the surrogate get called on non root objects? For completeness the Surrogate looks like this (testcode only to set a breakpoint):
sealed class StringSerializationSurrogate : ISerializationSurrogate
{
public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
{
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
string s = (String)obj;
return obj;
}
}