How to store setting with UWP C#?

620 views Asked by At

I a'm running an uwp app on Rasbperry Pi 3 with Windows 10 IoT OS via Visual Studio Remote Machine and Release is selected. The problem is how to save settings I have made and use the same settings when run same UWP app later.

How is it done? I can read the settings from the text file from Windows.ApplicationModel.Package.Current.InstalledLocation; But of course I can't save any changes to the same text file. Where exactly should I put the text file if I wan't to save changes to text file?

But perhaps I can use this

Windows.Storage.ApplicationData.Current.LocalSettings;

But how do I check if there is no value stored and put instead an default value?

With this I am trying to save these settings it doesn't work. The point with this is that I can use these same settings when I run the same uwp app again.

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["setting1"] = textBlockDelayValue.Text;
localSettings.Values["setting2"] = checkShow;
1

There are 1 answers

0
Rita Han On

Where exactly should I put the text file if I wan't to save changes to text file?

You can put the text file in Windows.Storage.ApplicationData.Current.LocalFolder of the solution and access it with this piece of code:

    Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    async void WriteFile()
    {
        StorageFile sampleFile = await localFolder.CreateFileAsync("test.txt",
            CreationCollisionOption.ReplaceExisting);
        await FileIO.WriteTextAsync(sampleFile, "111");
    }

    async void ReadFile()
    {
        try
        {
            StorageFile sampleFile = await localFolder.GetFileAsync("test.txt");
            String content = await FileIO.ReadTextAsync(sampleFile);
        }
        catch (Exception)
        {
            // Timestamp not found
        }
    }

But how do I check if there is no value stored and put instead an default value?

You can read them out like this:

        var value1 = ApplicationData.Current.LocalSettings.Values["setting1"];
        var value2 = ApplicationData.Current.LocalSettings.Values["setting2"];