Search code examples
c#jsonwindows-store-appsobservablecollectionwin-universal-app

Save/Get ObservableCollection to/from Roaming


I'm making a Universal windows store app and I have an ObservableCollection.

What I want is to save the data from the ObservableCollection somewhere so that the data can sync between desktop and phone that have the same universal app, and then I need to be able to get this data so that I can update the ObservableCollection.

I haven't done anything like this before, so I'm not sure how to proceed... Do I need to save this to an XML file, and if so, how will I sync it between the different devices. The only storage methods I know how to use are:

     ApplicationData.Current.LocalSettings.Values["key"] = "something"; 
     //Which stores "something" in local storage with key "key".

     ApplicationData.Current.RoamingSettings.Values["key"] = "something";
     //Which stores "something" in user's  Microsoft account storage with key "key".

Last one I think looks like to what I actually want, but it wouldn't be practical to save all my ObservableCollection items and properties like this.


Solution

  • The easiest way is to write it in a file in the app data roaming folder; app settings aren't very convenient to store collections. You can use XML, JSON or anything else. These days the trend is to use JSON, so here's an example.

    Serialization:

    var folder = ApplicationData.Current.RoamingFolder;
    var file = await folder.CreateFileAsync("collection.json", CreationCollisionOption.ReplaceExisting);
    using (var stream = await file.OpenStreamForWriteAsync())
    using (var writer = new StreamWriter(stream, Encoding.UTF8))
    {
        string json = JsonConvert.SerializeObject(collection);
        await writer.WriteAsync(json);
    }
    

    Deserialization:

    var folder = ApplicationData.Current.RoamingFolder;
    var file = await folder.GetFileAsync("collection.json");
    using (var stream = await file.OpenStreamForReadAsync())
    using (var reader = new StreamReader(stream, Encoding.UTF8))
    {
        string json = await reader.ReadToEndAsync();
        var collection = JsonConvert.DeserializeObject<ObservableCollection<YourClass>>(json);
    }
    

    (using JSON.NET)