0

I tried using BinaryFormatter and a class with one public field (a string) and yet, an identical class in another application couldn't deserialize it.

If possible, I'd like the class to contain a field of its own type (recursive) but if not - strings, ints, and byte arrays are the most important.

4

2 に答える 2

1

If you can't share a class library between applications, you can create a mirroring class in the client (consumer) application and map all its properties to the properties of the "initial" class + some auxillary info. This will be your proxy class. Then, you should take control over the deserialization process. For instance, use xml to hold data. You can encrypt the contents of the file and share the public key between applications if security is critical.

于 2012-09-05T15:56:29.877 に答える
1

The BinaryFormatter will include the full type name (assembly and namespace included) in the output. You need to use a custom SerializationBinder to read it:

public class CustomBinder : SerializationBinder
{
    static string assemblyToUse = typeof (MyObject).Assembly.FullName;
    public override Type BindToType(string assemblyName, string typeName)
    {
        if (typeName.EndsWith("MyType"))
            return typeof(MyTypeInThisAssembly);
        return base.BindToType(assemblyName, typeName);
    }
}


var formatter = new BinaryFormatter{Binder = new CustomBinder()};
var obj = formatter.Deserialize(...)

This has the downside of having to include the code for the CustomFormatter in every assembly tho, which I'm guessing is not what you want. This probably leaves you with having to use a custom format output (like JSON or protocol buffers )

于 2012-09-05T15:56:45.117 に答える