Pregunta

I need a collection of keys and values (like a dictionary) but it needs to be serializable using the Soapformatter.

Why the soapformatter?
I don't know the type that has to be serialized, I only know the interface that the type implements.

Does anyone have a clue how to crack this nut?

¿Fue útil?

Solución

Apparently all it takes is inheriting from Hashtable and adding the following constructors:

[Serializable]
public class StateContainer : Hashtable, IStateContainer
{
    public StateContainer() : base() { }
    public StateContainer(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

Took me half a day to figure this out...

you can then serialize this class like this:

XmlDocument xmlDocument = null;
using (MemoryStream memData = new MemoryStream())
{
    SoapFormatter formatter = new SoapFormatter();
    formatter.Serialize(memData, state);
    memData.Flush();
    memData.Position = 0;
    xmlDocument = new XmlDocument();
    xmlDocument.Load(memData);
}

And deserialize like this:

IStateContainer response = null;
using (MemoryStream memData = new MemoryStream())
{
    using (StreamWriter writer = new StreamWriter(memData))
    {
        writer.Write(state.stateobject);
        writer.Flush();
        memData.Flush();
        SoapFormatter formatter = new SoapFormatter();
        memData.Position = 0;
        response = (IStateContainer)formatter.Deserialize(memData);
    }
}

Hope this can help someone else out there some day :-)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top