In my MainWindow
, I have an ObservableCollection<Video>
called videos which holds Video objects. The class Video is marked as [Serializable]
(I also tried it as [Serializable()]
). I want to Serialize
and Deserialize
the whole collection with a BinaryFormatter
the following way:
Serialization:
BinaryFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream("Saves.bin",
FileMode.Create,
FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, videos);
}
Deserialization:
BinaryFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream("Saves.bin",
FileMode.Open,
FileAccess.Read,
FileShare.Read))
{
videos = (ObservableCollection<Video>)formatter.Deserialize(stream);
}
This DotNetPerls article demostrating the Serialization
of List
s operates similarly to my method, while a comment on this SO article suggests that the previous problem with the Serialization
of ObservableCollection
s does not persist in later versions of .Net (I'm using VS 2017 with the latest .Net). I do not store Window
objects in my project.
The error complains about the MainWindow
not marked as Serializable
when I populate my UI elements with the underlying data loaded into the fields using DataBinding
, when I load the data only, the error refers to Window
not marked as Serializable
, instead of the MainWindow
.
I had problems with Events
, but I marked them with the [field: NonSerialized()]
attribute, so this is not the problem (at least I would not think so).
So what am I doing wrong? Why does the formatter want to serialize MainWindow
in the first place? Should I use XMLSerialization
instead of BinaryFormatter
?
EDIT: I tried the exact same syntax as shown in the Perls article, but it gave the same results.