How to save a list of objects in UWP?

Logan Stach 41 Reputation points
2020-01-09T13:32:16.787+00:00

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)
No comments
{count} votes

Accepted answer
  1. 2020-01-09T14:41:16.68+00:00

    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());
    
    No comments

1 additional answer

Sort by: Most helpful
  1. macintoshpro 36 Reputation points
    2020-01-09T14:52:53.72+00:00

    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)
    
    No comments