Question

I have a class I serialize to a file, ie. myfile01.myfile. I'm using binary serialization (not xml).

In version 1 of this class, there was a field 'ColoredFont'. This is a class that contains a Font and a Color.

In version 2 of the class, the class ColoredFont was changed, and the 'Font' field was replaced by 'SerializableFont'.

Now the problem: when i want to open version 1 files, I get an error :

 Object of type 'System.Drawing.Font' cannot be converted to 
 type 'Project.SerializableFont'.

I already use a custom serialization binder

public class Binder : SerializationBinder {

    public override Type BindToType(string assemblyName, string typeName) {
        Type tyType = null;
        string sShortAssemblyName = assemblyName.Split(',')[0];
        Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
        if (sShortAssemblyName.ToLower() == "project"
            || sShortAssemblyName == "SoftwareV_3.0"  )
        {
            sShortAssemblyName = "SoftwareV_4.0";
        }
           foreach (Assembly ayAssembly in ayAssemblies) {
               if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0]) {
                tyType = ayAssembly.GetType(typeName);
                break;
            }
        }
        return tyType;
    }
}

How I can tell the deserialization to convert System.Drawing.Font to SerializableFont ??

Was it helpful?

Solution

Try this for the ColoredFont class :

[Serializable]
public class ColoredFont : ISerializable
{
    public SerializableFont SerializableFont;
    public Color Color;

    private ColoredFont(SerializationInfo info, StreamingContext context)
    {
        Color = (Color)info.GetValue("Color", typeof(Color));
        try
        {
            SerializableFont = (SerializableFont)info.GetValue("SerializableFont", typeof(SerializableFont));
        }
        catch (SerializationException serEx)
        {
            Font f = (Font)info.GetValue("Font", typeof(Font));
            // do something to initialize SerializedFont from 'f'
        }

    }

    #region ISerializable Members

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("SerializableFont", SerializableFont);
        info.AddValue("Color", Color);
    }

    #endregion
}

OTHER TIPS

You must return the new type Project.SerializableFont when asked for typename ==System.Drawing.Font.

EDIT : You must compare Font and SerializableFont only as the given typename is expected to be the name of the class regardless of the namespace but I'm not sure. Then return typeof(SerializableFont)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top