Serialise and De-Serialise Helpers for ObservableCollection

I recently came across a need to serialise and de-serialise an ObservableCollection from an MVVMCross application. To achieve this, I created a couple of helper methods which I’d like to share.

Both use the MVVM Cross File plug-in.

Serialise

        public static void Serialise<T>(ObservableCollection<T> collection, string fileName)
        {
            var file = Mvx.Resolve<IMvxFileStore>();
            var fileData = file.OpenWrite(fileName);

            DataContractSerializer serializer = new
                        DataContractSerializer(typeof(ObservableCollection<T>));
            serializer.WriteObject(fileData, collection);
            fileData.Flush();
        }

De-serialise

        public static ObservableCollection<T> DeSerialise<T>(string fileName)
        {
            var file = Mvx.Resolve<IMvxFileStore>();
            if (!file.Exists(fileName))
                return null;

            var fileData = file.OpenRead(fileName);
            if (!fileData.CanRead || fileData.Length == 0)
                return null;

            DataContractSerializer serializer = new
                        DataContractSerializer(typeof(ObservableCollection<T>));

            ObservableCollection<T> data = (ObservableCollection<T>)serializer.ReadObject(fileData);
            return data;
        }

The Serialise method can be wrapped in an extension method, too:

        public static void Serialise<T>(this ObservableCollection<T> collection, string fileName)
        {
            Helpers.SerialiseHelper.Serialise(collection, fileName);
        }

Obviously, the `DeSerialise` cannot, as it would change the object that you are extending.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.