UWP - How completely delete all data written in LocalSettings?

2.5k views Asked by At

I'm working on a UWP app and I need data to be stored as the setting.

I use ApplicationData.Current.LocalSettings and I store a mix of simple data and composite data in it. When my app user wants to end its session, I want all data that I stored before, to be deleted. I used ApplicationData.Current.ClearAsync(), ApplicationData.Current.LocalSettings.Values.Clear() and it seems it works but when I check settings.dat file which is where those settings are stored, I see data is still there and only their connection with their keys are cleared and made them unavailable.

The problem is from version to version there are situations that I need to change some of the keys or even stop using some of them and with this issue I described, data related to previous keys will remain in settings.dat and file size grows over time.

I need a solution to let me clear settings.dat content (or at least contents which I've written in it) completely.

1

There are 1 answers

6
Razor On BEST ANSWER

You are not clearing the local settings here. The ApplicationDataContainer.Values returns a PropertySet and the Clear method corresponds to the Collection class. So it clears only the collection you get and not the settings. You must use the Remove method to individually remove a setting based on a key or use an ApplicationDataContainer to store your settings. You can delete all the settings stored in the container in one go. Remove a setting individually by its key:

ApplicationData.Current.LocalSettings.Values.Remove("key");

Create ApplicationDataContainer:

var LocalSettingsContainer = ApplicationData.Current.LocalSettings;
var container = LocalSettingsContainer.CreateContainer("ContainerName", ApplicationDataCreateDisposition.Always);

Add Settings to Container:

container.Values[Key] = Value;

Delete a container:

LocalSettingsContainer.DeleteContainer("containerName");

PS: Do note that if you have any sub containers within the container you're about to delete both the settings in the specified container along with the sub containers will get deleted. More about localsettings can be found in the documentation.

Edit: You can get the Keys in the ApplicationDataContainer by casting the ApplicationDataContainer.Values to ApplicationDataContainerSettings which has Keys property by which you can remove the setting individually.

var containerSettings = (ApplicationDataContainerSettings)ApplicationData.Current.LocalSettings.Values;
var keys = containerSettings.Keys;