Resolved How to save a custom ObservableDictionary to a file, and restore it later?

RickGove

New member
Joined
Jan 23, 2021
Messages
2
Programming Experience
Beginner
I'm not sure if I'm using any of the right language, and I'm a beginner...

I have created an ObservableDictionary like so:

ObservableDictionary.cs:
[Serializable]
    public class ObservableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, INotifyCollectionChanged
    {
        public ObservableDictionary() : base() { }
        public ObservableDictionary(int capacity) : base(capacity) { }
        public ObservableDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { }
        public ObservableDictionary(IDictionary<TKey, TValue> dictionary) : base(dictionary) { }
        public ObservableDictionary(int capacity, IEqualityComparer<TKey> comparer) : base(capacity, comparer) { }
        public ObservableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : base(dictionary, comparer) { }

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        public new TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set
            {
                OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, key, 0));
                base[key] = value;
            }
        }

        public new void Add(TKey key, TValue value)
        {
            base.Add(key, value);
            Storage.Save(this, "./cache.txt", false);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, key, 0));
        }

        public new bool Remove(TKey key)
        {
            bool x = base.Remove(key);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, key, 0));
            return x;
        }

        public new void Clear()
        {
            base.Clear();
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }


        protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (CollectionChanged != null)
            {
                CollectionChanged(this, e);
            }
        }
    }

I need to be able to save this to a file in unreadable binary format, and restore on the next load of the program...

These are the methods I have used, but I can't get them to work...

Storage.cs:
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
        {
            using Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create);
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);
        }
        
public static ObservableDictionary<> ReadFromBinaryFile<T>(string filePath)
        {
            using (Stream stream = File.Open(filePath, FileMode.Open))
            {
                var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                return (T)binaryFormatter.Deserialize(stream);
            }
        }

Please help me... Thank you in advance.
 
A couple things stand out from what you've posted above.

You can't just append to an existing file that contains serialized data and then expect the deserializer to find the old data and the newly appended data and somehow have the deserializer combine the two chunks of data together.

ReadeFromBinaryFile<T>() should return an object of type T (based on your line 13). It should not return a generic ObservableDictionary<> like you declared on line 8. Furthermore it would make better sense (and seem symmetrical) that if you called WriteToBinaryFile<MyObjectType>("myfille.bin", myObject); that you later call MyObjectType myObject = ReadFromBinaryFile<MyObjectType>("myfile.bin");

It doesn't really make sense to serialize an ObservervableDictionary because "observable" implies that there maybe various other objects which are listening to the CollectionChanged event of the object. Are you realistically going to be able to save the list of those other objects during serialization, and then when you deserialize hook up the event handlers for those other objects again? What happens when you serialize now, restart the computer, then re-run the program and deserialize? There is no guarantee that the program will reload into the same memory addresses, nor that the objects allocated within the program will have the same memory addresses/offsets. A Dictionary<TKey, TValue> is already serializable on its own. There is no need to make a serializable observable dictionary.
 
Back
Top Bottom