Reputation: 61
I use MVVM for my solution in my UWP app. I have a class called Settings. I want to store that on disc. How can I do that?
Upvotes: 3
Views: 3326
Reputation: 3157
The best way is to use ApplicationData.LocalSettings. Remember that this should be used only to store settings and user preferences (not user data like files or objects).
To store settings please use below code:
//Get reference to LocalSettings:
var localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values["ServiceAddress"] = "<<Address of your service to store>>";
To get value from the Settings please use below code:
var serviceAddressFromSettings = localSettings.Values["ServiceAddress"].ToString();
Remember to cast the value.
Upvotes: 8
Reputation: 1967
If you want to store settings pertaining to the application I would suggest you use ApplicationData.LocalSettings.
With this you don't need to explicitly specify to read/write from a file making the job of saving the settings very easy.
Upvotes: 1
Reputation: 1236
What I do is use JSON.NET to serialize and deserialize a class to a JSON string that can be stored. This is a static class I mostly use in my solutions:
public static class SettingsService
{
private const string SETTINGS_FILENAME = "Settings.json";
private static StorageFolder _settingsFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
public async static Task<Settings> LoadSettings()
{
try
{
StorageFile sf = await _settingsFolder.GetFileAsync(SETTINGS_FILENAME);
if (sf == null) return null;
string content = await FileIO.ReadTextAsync(sf);
return JsonConvert.DeserializeObject<Settings>(content);
}
catch
{ return null; }
}
public async static Task<bool> SaveSettings(Settings data)
{
try
{
StorageFile file = await _settingsFolder.CreateFileAsync(SETTINGS_FILENAME, CreationCollisionOption.ReplaceExisting);
string content = JsonConvert.SerializeObject(data);
await FileIO.WriteTextAsync(file, content);
return true;
}
catch
{
return false;
}
}
}
In this case I store the settings in the local user folder (not roamed). You can also store it in the roaming application folder, so the settings can roam to other machines for the user as well. To save settings:
Settings settings = new Settings();
await SettingsService.SaveSettings(settings);
To load settings:
Settings settings = await SettingsService.LoadSettings();
Be careful that not all types can be serialized. Properties you want to exclude can get an [JsonIgnore]
attribute.
Upvotes: 1