views:

31

answers:

2

How can I serialize a list of Exception objects (also including derived exceptions, eg. FileNotFoundException) with the DataContractSerializer?

I always get an error about the serializer not knowing the types in the list so i devised a workaround.

It looked something like this:

   Dim XmlSerializer As New DataContractSerializer(ExceptionsList.GetType(), ExceptionsList.Select(Function(i) i.GetType))
   XmlSerializer.WriteObject(Stream, List)

This works. I just add all the different exception types to the list of known types and it works. But on deserialization I am stuck. The problem is i dont know the types of exceptions stored in the file beforehand.

Any ideas?

A: 

I think you're SOL. The serializer needs to know the types that might be in the input.

You could try using the NetDataContractSerializer. That outputs type metadata in addition to the data being serialized.

John Saunders
This works thanks, I wonder why you can't just do this with the regular serializer.
prof23030
Because the regular serializer just serializes to XML that is interoperable. You need to tell it what types are possible, otherwise it can't deserialize. The `NetDataContractSerializer` gets around this by adding type metadata to the XML. This is also why you can't use it to communicate to a non-.NET service or client.
John Saunders
I just found out that the NetDataContractSerializer cannot serialize in medium trust (i am on shared hosting, if i try to serialize i get security exception), so i guess i'll have to find another way.
prof23030
A: 

You might try unboxing the Exceptions going into the serializer to System.Exception. I don't if this would have any real impact, but at least the type passing through might register as something standard.

(shot in the dark)

Joel Etherton