Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Cross Platform File Storage with PCLStorage NuGet Package

Before I can get onto using the SharedAccessSignature to upload content to Blob storage I first need to generate and save content. As this relies on platform specific implementations of capturing images from the camera and then accessing the file system. I’ll start with the latter and I’ll use a NuGet package called PCLStorage which has implementations for all the platforms I’m interested in. From NuGet I locate the PCLStorage package and install it into the client applications.

image

In my MainViewModel I’ve added the following WriteFile and ReadFile methods that for the time being will write and read an simple text file:

private string fileText;

public string FileText
{
    get { return fileText; }
    set
    {
        if (FileText == value) return;
        fileText = value;
        OnPropertyChanged();
    }
}

public async Task WriteFile()

{
    var file =
        await
            FileSystem.Current.LocalStorage.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
    using(var stream = await file.OpenAsync(FileAccess.ReadAndWrite))
        using(var writer = new StreamWriter(stream))
        {
            await writer.WriteAsync(FileText);
        }
}
public async Task ReadFile()
{
    var file =
        await
            FileSystem.Current.LocalStorage.GetFileAsync("test.txt");
    using (var stream = await file.OpenAsync(FileAccess.Read))
    using (var reader= new StreamReader(stream))
    {
        FileText = await reader.ReadToEndAsync();
    }
}

The FileText property can be databound to a TextBox in the XAML based projects allowing for user input which will be persisted between application instances. The actual location of the file is platform specific, for example on WPF this file is located at C:\Users\Nick\AppData\Local\RealEstateInspector\RealEstateInspector.Desktop\1.0.0.0\test.txt which is local data specific to both user and application. PCLStorage also defines a roaming storage option which again will be dependent on the platform implementation.

Pingbacks and trackbacks (2)+

Comments are closed