Luis Valencia - MVP Luis Valencia - MVP - 1 month ago 12
C# Question

How to save application settings?

We have a UWP for Windows IoT Core, we need to save some settings, but these settings have to live even if the application is stopped or the IoT device restarted.

The code I have is the following, it works perfectly fine when the app is open, and if I switch between XAML pages, but doesn't work when the application is stopped, it's like the variable never existed.

static class Global
{
public static Windows.Storage.ApplicationDataContainer localSettings { get; set; }
public static Windows.Storage.StorageFolder localFolder { get; set; }
}

private void Btn_Inciar_Config_Click(object sender, RoutedEventArgs e)
{
if (TxtDeviceKey.Text != String.Empty || TxtDeviceName.Text != String.Empty || Txt_Humedad_Config.Text != String.Empty || Txt_Intervalo_Config.Text != String.Empty || Txt_Temperatura_Ambiente_Config.Text != String.Empty || Txt_Temperaura_Config.Text != String.Empty)
{
Windows.Storage.ApplicationDataCompositeValue composite =
new Windows.Storage.ApplicationDataCompositeValue();
composite["GlobalDeviceKey"] = TxtDeviceKey.Text;
composite["GlobalDeviceName"] = TxtDeviceName.Text;
composite["GlobalTemperature"] = Txt_Temperaura_Config.Text;
composite["GlobalHumidity"] = Txt_Humedad_Config.Text;
composite["GlobalTemperatureRoom"] = Txt_Temperatura_Ambiente_Config.Text;
composite["GlobalInterval"] = Txt_Intervalo_Config.Text;

localSettings.Values["ConfigDevice"] = composite;
Lbl_Error.Text = "";
Frame.Navigate(typeof(MainPage));
}
else
{
Lbl_Error.Text = "Ingrese todos los campos de configuracion";
}
}

Answer

If you want to store your settings locally you can store them as single items or as a ApplicationDataCompositeValue (to keep all values as a single entity) like you did. Just put the composite (or single items) in the ApplicationData.Current.LocalSettings container. Below a small piece of code that you can simply copy paste in an empty app and attach to 2 buttons to try out.

private void SaveClicked(object sender, RoutedEventArgs e)
{
    Windows.Storage.ApplicationDataCompositeValue composite =
        new Windows.Storage.ApplicationDataCompositeValue();
    composite["GlobalDeviceKey"] = "Key";
    composite["GlobalDeviceName"] = "Name";
    ApplicationData.Current.LocalSettings.Values["ConfigDevice"] = composite;
}

private void LoadClicked(object sender, RoutedEventArgs e)
{
    Windows.Storage.ApplicationDataCompositeValue composite =
        (ApplicationDataCompositeValue) ApplicationData.Current.LocalSettings.Values["ConfigDevice"];
    var key = (string)composite["GlobalDeviceKey"];
}
Comments