Search code examples
c#arrayssavewinui

Save an array to Windows.Storage.ApplicationData.Current.LocalSettings (C# + WinUI3)


I just started learning WinUI 3 and I am currently trying to make a little todo app. I want to save the data of the lists so I can keep it even if the application is closed. Microsoft recommends using:

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

And then using:

localSettings.Values["Datakey"]

to access the data.

This works well for data types like stings, ints etc. However, when I try to save an array that way, it gives me an error:

//Get data of the list boxes as save it to an array
string[] doneItems = lsbTasksDone.Items.OfType<string>().ToArray();
string[] undoneItems = lsbTasksUndone.Items.OfType<string>().ToArray();

//Save arrays to localSettings
localSettings.Values["ToDoDoneSaveData"] = doneItems;
localSettings.Values["ToDoUndoneSaveData"] = undoneItems;

Error: System.Runtime.InteropServices.COMException: "Incorrect size argument."

I couldn't really find any info on that error.

How do I save that array?

Regards, LightJack


Solution

  • You can persists arrays into the ApplicationData class, however there are strict size limitations. Namely, entries cannot exceed 8KB in size or 64KB if using ApplicationDataCompositeValue. The following code works:

    localSettings.Values["Demo"] = new string[10];
    

    while this fails as it is exceeding the space limitation:

    localSettings.Values["Demo"] = new string[10000];