views:

329

answers:

2

I'm using C# with .NET 3.5.

I am using the System.Configuration.ApplicationSettingsBase class to load and save application settings. One of the settings I would like to preserve is an in-memory System.Data.DataTable. The DataTable contains just two columns of type UInt32 and System.Net.IPAddress, respectively. When I call the Save() function on the ApplicationSettingsBase, I get the following exception:

InvalidOperationException: System.Net.IPAddress cannot be serialized because it does not have a parameterless constructor.

If I just use a System.Net.IPAddress object as the setting instead of the DataTable, I do not have a problem. There's something about it being in the DataTable that is causing the exception.

Any ideas what might be going on? Any ideas on how to fix it?

+1  A: 

The error explains the problem- store it as a string instead. If you need to use the IPAddress class you can use ToString and Parse to convert between the two. The error will be due to the way DataTable does the serialization.

Try this code:

IPAddress ip = IPAddress.Parse("192.168.0.1");
XmlSerializer serializer = new XmlSerializer(typeof(IPAddress));  
MemoryStream ms = new MemoryStream();
serializer.Serialize(ms, ip);

Then try this:

IPAddress ip = IPAddress.Parse("192.168.0.1");
BinaryFormatter serializer = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
serializer.Serialize(ms, ip);

You will see that when you put the IPAddress object in a datatable the XmlSerializer is used by default.

Interestingly try changing the RemotingFormat property to binary, I believe this may fix the issue. DataTable.RemotingFormat

RichardOD
That certainly is one way to fix it, but it doesn't explain why the problem exists. Why does serializing the DataTable require IPAddress to have a parameterless constructor when I can serialize an IPAddress object directly without any problem?
Matt Davis
@Matt- I've added a code sample now.
RichardOD
Bingo! That's what I was looking for. Thanks!
Matt Davis
I remember they changed how you could Serialize datatables in .NET 2.0 but I couldn't for life of me remember what the property was called. Glad it has fixed your issue.
RichardOD
A: 

I think the XmlElementAttribute might solve your problem

slf
How would I apply the XmlElementAttribute to the IPAddress column of the DataTable?
Matt Davis