// Listing 16-5
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;

class StateStore
{
    public static async Task SaveString(string fileName, string value)
    {
        StorageFolder folder = ApplicationData.Current.LocalFolder;
        StorageFile file = await folder.CreateFileAsync(fileName,
            CreationCollisionOption.ReplaceExisting);
        using (IRandomAccessStream runtimeStream =
                   await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            IOutputStream output = runtimeStream.GetOutputStreamAt(0);
            byte[] valueBytes = Encoding.UTF8.GetBytes(value);
            await output.WriteAsync(valueBytes.AsBuffer());
        }
    }

    public static async Task<string> FetchString(string fileName)
    {
        StorageFolder folder = ApplicationData.Current.LocalFolder;
        StorageFile file = await folder.GetFileAsync(fileName);
        using (IRandomAccessStream runtimeStream = await file.OpenReadAsync())
        {
            IInputStream input = runtimeStream.GetInputStreamAt(0);
            var size = (uint) (await file.GetBasicPropertiesAsync()).Size;
            var buffer = new byte[size];
            await input.ReadAsync(
                buffer.AsBuffer(), size, InputStreamOptions.Partial);
            return Encoding.UTF8.GetString(buffer, 0, (int)size);
        }
    }
}
