How to serialize the object of type DateTimeFormatInfo?

330 Views Asked by At

I want to serialize the object of type DatetimeFormatInfo.

I tried the following code:

DateTimeFormatInfo dateTimeFormat = new DateTimeFormatInfo();
dateTimeFormat.ShortDatePattern = "dd-MMM-yy";
xs = new XmlSerializer(dateTimeFormat.GetType());
StreamWriter sw = new StreamWriter("Setting.xml");
xs.Serialize(sw, dateTimeFormat);

But it throws the below exception.

System.InvalidOperationException was unhandled.
There was an error generating the XML document.
The type System.Globalization.GregorianCalendar was not expected.
Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

Is anything I need to add for serializing DateTimeFormatInfo?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to include in the XmlSerializer a list of addictional object types to serialize. In your case, you need to add the object type System.Globalization.GregorianCalendar.

        System.Globalization.DateTimeFormatInfo dateTimeFormat = new System.Globalization.DateTimeFormatInfo();
        dateTimeFormat.ShortDatePattern = "dd-MMM-yy";

        // Add here all the extra types you need to serialize
        Type[] extraTypes = new Type[] { typeof(System.Globalization.GregorianCalendar) };

        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(dateTimeFormat.GetType(), extraTypes);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(@"c:\testso.xml");
        xs.Serialize(sw, dateTimeFormat);