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.