Kasun Wanniarachchi
Kasun Wanniarachchi

Reputation: 327

Can not save setting in roaming/local setting

I need to save the setting in either roaming or local settings. The problem is when i execute the program it shows that setting are stored with a given key and those setting can be retrieved back as well. But when i re-execute or execute the same program later, those saved setting are lost. It again creates them!!

Why setting are not getting saved?

To set the setting, i use following code (setting is a string, value is an object)

ApplicationData.Current.LocalSettings.Values.Add(setting, value);

ApplicationData.Current.RoamingSettings.Values.Add(setting, value);

To retrieve setting, i use following code

ApplicationData.Current.RoamingSettings.Values[setting];

What's the problem with this code?

Upvotes: 0

Views: 1320

Answers (2)

Kasun Wanniarachchi
Kasun Wanniarachchi

Reputation: 327

I was doing a blunder by debugging a test method so setting will not be saved permanently. If you execute your App all your setting will be saved with the above simple coding.

Upvotes: 1

Damir Arh
Damir Arh

Reputation: 17855

Your code should work just fine. Maybe there's a problem in the logic you're using to decide between reading the value and writing a value back.

Try putting something like this at the startup of your app:

object settingValue = "InitValue";

if (ApplicationData.Current.LocalSettings.Values.ContainsKey(settingKey))
{
    settingValue = ApplicationData.Current.LocalSettings.Values[settingKey];
}
else
{
    ApplicationData.Current.LocalSettings.Values[settingKey] = settingValue;
}

You basically need to read the setting if it exists or initialize it when it doesn't.

Also, keep in mind that local settings get deleted when the app is uninstalled and reinstalled. Visual Studio sometimes does this when you make change application manifest.

Upvotes: 1

Related Questions