Tuesday, 11 July 2017

Roaming folder

if for some reason the roaming settings doesn't suit your needs there's also a roaming folder, however it's included in the 100k limit that once surpassed will not notify you or work.

<Page
    x:Class="pc.NavigateExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBox x:Name="Input_TextBox" />
            <Button x:Name="Save_Button" Click="Save_Button_Click" Content="Save"/>
        </StackPanel>
    </Grid>
</Page>


above we have the same xaml UI as we did before and below we use the roaming folder to store and load our parameter.

using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Core;

namespace pc.NavigateExample
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            InitializeComponent();

            Task.Run(async () =>
            {
                var roamingFolder = ApplicationData.Current.RoamingFolder;
                var storageFile = await roamingFolder.GetFileAsync("data.txt");

                if (storageFile != null)
                    return storageFile;

                throw new ArgumentNullException();
            }).ContinueWith(async tr =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    if (tr.Status == TaskStatus.Faulted)
                       await new MessageDialog("No File detected").ShowAsync();
                    else
                        Input_TextBox.Text = await FileIO.ReadTextAsync(tr.Result);
                });
            });
        }

        async void Save_Button_Click(object sender, RoutedEventArgs e)
        {

            var parameter = Input_TextBox.Text;
            var roamingFolder = ApplicationData.Current.RoamingFolder;
            var storageFile = await roamingFolder.CreateFileAsync("data.txt",
                                    CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(storageFile, parameter);
        }
    }
}

Now in our save button click event handler we just commit our value to a data.txt file in our roaming folder. The load is however a bit trickier since constructors can't be marked as async we create a background task that tries to get our "data.txt" file from our roaming folder, if the file isn't available we raise an exception. Then in the continuewith if there was an exception we display a message dialogue and if we successfully got our data.txt file we load it's contents into the textbox.