1

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 Lists operates similarly to my method, while a comment on this SO article suggests that the previous problem with the Serialization of ObservableCollections 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.

oneManArmin
  • 606
  • 6
  • 24
  • 1
    Does your Video class keep a reference to the Window? – Barracoder Jul 18 '17 at 14:35
  • No, whenever I use one of my `window` objects in a method, I keep reinitializing them like in NumberSelector num = new NumberSelector(); inside the method. – oneManArmin Jul 18 '17 at 14:45
  • Interestingly, XMLserialization works after some tweaking and modifications to the code: the XMLSerializer throw an error, for example, that my code has _circular reference_ to objects. This _was_ actually the case, because I wanted to keep a reference of the parent in every child element, but I replaced it now with an event-based implementation and it works fine. Could this be the reason behind the previous error? – oneManArmin Jul 18 '17 at 20:49
  • 1
    Please show us your `Video` class and how exactly you populate your data. – dymanoid Jul 19 '17 at 12:38

0 Answers0