I am trying to serialize a class object and ran into a problem when I added a System.Timers.Timer object.
During serialization, I am getting the following exception:
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
Additional information: Type 'System.Timers.Timer' in Assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
The project is .net 4.6 Windows Forms application
Here is the class I am serializing:
using System;
using System.Xml.Serialization;
[Serializable]
[XmlInclude(typeof(CTestClass))]
public class CTestClass
{
public CTestClass()
{
x = 1;
timer = new System.Timers.Timer();
}
[XmlElement]
public int x { get; set; }
// It seems [XmlIgnore] is being ignored... :-(
[XmlIgnore]
public System.Timers.Timer timer { get; set; }
}
Here is the code that I am using to serialize the class object:
( NOTE: use of the BinaryFormatter is required )
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
private void TestIt()
{
CTestClass ctc = new CTestClass();
SerializeData(ctc);
}
protected virtual byte[] SerializeData(CTestClass data)
{
using (var memoryStream = new MemoryStream())
{
new BinaryFormatter().Serialize(memoryStream, data);
return memoryStream.ToArray();
}
}
From the Comments:
Setting the property to private - didn't help
private System.Timers.Timer timer { get; set; }
using [NonSerialized] - didn't help:
Error CS0592 Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations. TimerSerializationError c:\TimerSerializationError\TimerSerializationError\CTestClass.cs 19 Active
"specifically not using an auto-property--(i.e. no get-set)" - didn't help:
Additional information: Type 'System.Timers.Timer' in Assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.