views:

32

answers:

1

I have a class in my C# project marked with the [Serializable] attribute. It has a property of type RSAKeyValue:

[XmlElement(PUBLIC_KEY_TAG_NAME)]
public RSAKeyValue Key { get; private set; }

When I try to serialize an instance of my class to XML and then deserialize that XML back to an instance of my class, I get:

System.InvalidOperationException: System.Security.Cryptography.KeySizes cannot be serialized because it does not have a parameterless constructor.

This occurs when I call XmlSerializer.Serialize. I'm sure it's because of the RSAKeyValue property in my class since all the other properties that get serialized are simple strings. What can I do about this? Should I maybe make my own wrapper class around an RSAKeyValue instance that properly serializes/deserializes?

Here is some sample XML that could be deserialized into an RSAKeyValue instance:

<RSAKeyValue>
  <Modulus>long string here...</Modulus>
  <Exponent>short string here</Exponent>
</RSAKeyValue>
A: 

First of all, the XML Serializer ignores the [Serializable] attribute.

Second, if the class does not have a default constructor, then you can't serialize it using the XML Serializer, period.

What are you trying to accomplish? Perhaps you can accomplish the same thing using the Data Contract Serializer?


Create a class that contains just a Modulus and an Exponent. Fill that class from an RSAKeyValue. Serialize your custom class. After deserializing, use it to create a new RSAKeyValue.

John Saunders
I want to be able to store the Modulus and Exponent parts of the `RSAKeyValue` in an XML document alongside other data. I want to be able to read XML from a file and have it parsed out into an instance of my class, then access the `Key` property and get an instance of some class containing the Modulus and Exponent that were stored in the XML.
Sarah Vessels
Then you just answered your own question. Create a class that contains just a Modulus and an Exponent. Fill that class from an RSAKeyValue. Serialize your custom class. After deserializing, use it to create a new RSAKeyValue.
John Saunders
Hmph. With your fancy ideas... ;) Working on that now; thanks!
Sarah Vessels
John, you should post your comment as an answer, because that's what I ended up doing and it worked for me. I'd mark yours as the selected answer!
Sarah Vessels