How to save a list of objects in UWP?

Logan Stach 41 Reputation points

I have a list of objects with class attributes in my UWP app. How do I save the list of objects so that they are still there when the user closes the program?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,861 Reputation points

    In general, we often serialize the object then store to the local store with Json.NET

    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    var list = new List() ;
    for (int i = 0; i < 15; i++)
        list.Add(new People { Name = $"Nico{i}", Age = i + 1 });
    string json = JsonConvert.SerializeObject(list);
    // Create a simple setting.
    localSettings.Values["exampleList"] = json;
    // Read data from a simple setting.
    Object value = localSettings.Values["exampleList"];
    var ReList = JsonConvert.DeserializeObject > (value.ToString());
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. macintoshpro 36 Reputation points

    If the object is too big, save it to LocalSettings will throw an exception. A safe method is create a file in LocalFolder and save to it, we will convert object to text using JsonConvert.SerializeObject

    Write Data

    StorageFile sampleFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
    await Windows.Storage.FileIO.WriteTextAsync(sampleFile, JsonConvert.SerializeObject(list));

    Read Data

    StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    StorageFile file = await folder.GetFileAsync(fileName);
    var text = await FileIO.ReadTextAsync(file);
    var object = JsonConvert.DeserializeObject(text)
    0 comments No comments