question

LoganStach-1629 avatar image
0 Votes"
LoganStach-1629 asked ·

How to save a list of objects in UWP?

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?

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

NicoZhu-MSFT avatar image
0 Votes"
NicoZhu-MSFT answered ·

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




· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

macintoshpro avatar image
0 Votes"
macintoshpro answered ·

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)
· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.