Here’s my code:
[Serializable()]
public class Project
{
private List<string> _Kinds = new List<string>();
public DataTable ExtractedElementsTable;
public Project()
{
ExtractedElementsTable = new DataTable();
ExtractedElementsTable.TableName = "Output";
}
public List<string> Kinds
{
get { return _Kinds; }
set { _Kinds = value; }
}
}
When, after adding some stuff to the List<string> _Kinds, I try to serialize the whole Poject, and then deserialize it, the _Kinds list is empty. But if I comment out all the three lines where ExtractedElementsTable is referenced, it works ok. Here’s is my serializing and deserializing code (note the currentProject.Kinds.Add("hi"); line in the serializing code. currentProject is just an instance of Project.
private void openButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Stream stream = File.Open(openFileDialog1.FileName, FileMode.Open);
XmlSerializer xmlFormatter = new XmlSerializer(currentProject.GetType());
currentProject = (Project)xmlFormatter.Deserialize(stream);
stream.Close();
}
}
private void saveButton_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
currentProject.Kinds.Add("hi");
Stream stream = File.Open(saveFileDialog1.FileName, FileMode.Create);
XmlSerializer xmlFormatter = new XmlSerializer(currentProject.GetType());
xmlFormatter.Serialize(stream, currentProject);
stream.Close();
}
}
Change the DataTable field to a DataSet field.
I ran quite a few test. The Kinds property gets serialized with all the items. But does not deserialize properly. However, I changed the DataTable field to a DataSet and it all worked fine.