Search code examples
c#exceptionserializationcompact-framework

In C#, how can I serialize System.Exception? (.Net CF 2.0)


I want to write an Exception to an MS Message Queue. When I attempt it I get an exception. So I tried simplifying it by using the XmlSerializer which still raises an exception, but it gave me a bit more info:

{"There was an error reflecting type 'System.Exception'."}

with InnerException:

{"Cannot serialize member System.Exception.Data of type System.Collections.IDictionary, because it implements IDictionary."}

Sample Code:

        Exception e = new Exception("Hello, world!");
        MemoryStream stream = new MemoryStream();
        XmlSerializer x = new XmlSerializer(e.GetType()); // Exception raised on this line

        x.Serialize(stream, e);
        stream.Close();

EDIT: I tried to keep this a simple as possible, but I may have overdone it. I want the whole bit, stack trace, message, custom exception type, and custom exception properties. I may even want to throw the exception again.


Solution

  • I think you basically have two options:

    1. Do your own manual serialization (probably do NOT want to do that). XML serialization will surely not work due to the exact message you get in the inner exception.
    2. Create your own custom (serializable) exception class, inject data from the thrown Exception into your custom one and serialize that.