Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialization – serialize the properties in user control

How to serialize the properties in user control?

I have tried the following code but I got InvalidOperationExceptio, While creating the XmlSerializer object

MyUserControl userControl = new MyUserControl();
XmlSerializer serializer = new XmlSerializer(typeof(MyUserControl));
Stream stream = new MemoryStream();
TextWriter writer = new StreamWriter(stream);
serializer.Serialize(writer, userControl);   

Exception:

System.InvalidOperationException was unhandled

HResult=-2146233079

Message=There was an error reflecting type 'Demo.MyUserControl'.

like image 814
Ponraja Avatar asked Dec 21 '25 15:12

Ponraja


1 Answers

You should not do it like this IMHO.

You should write a separate "Data Transfer Object (DTO)" style class to hold the data that you want to serialize, and use that instead. (You'd need to write Transform methods to convert the data back and forth of course.)

Otherwise you will couple your data storage format tightly to your user control.

If you use a separate class for serializing, it will make it much more manageable and flexible especially if you need to add new properties in the future.

If you really must serialize the user control (and I highly recommend that you don't) you could try using DataContract serialization which has an "opt-in" mechanism for which properties get serialized, rather than the "opt-out" mechanism for the older serialization.

like image 51
Matthew Watson Avatar answered Dec 23 '25 05:12

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!