Code snippet for reading files in a Windows Store App

Here’s a little useful code snippet for opening up a file stream from either you local data store, or from the application folder in a Windows Store/WinRT/Metro/[insert name of the day] app:

using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
//[...]
public static async Task<Stream> ReadFile(string filename)
{
    StorageFolder folder = null;
    if (filename.StartsWith("ms-appx:///"))
    {
        filename = filename.Substring(11);
        folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    }
    else
    {
        folder = Windows.Storage.ApplicationData.Current.LocalFolder;
    }
    while (filename.Contains("/"))
    {
        var foldername = filename.Substring(0, filename.IndexOf('/'));
        filename = filename.Substring(foldername.Length + 1);
        folder = await folder.GetFolderAsync(foldername).AsTask().ConfigureAwait(false);
    }
    var file = await folder.GetFileAsync(filename);
    IInputStream stream = await file.OpenReadAsync();
    DataReader reader = new DataReader(stream);
    return await file.OpenStreamForReadAsync();
}

This allows you to get access to a stream from your application. Ie. if you have a file called “About.txt” in your project inside the folder “Assets” (remember to set build action to ‘content’), you would access it like this:

using (var stream = await ReadFile("ms-appx:///Assets/About.txt"))
{
    //TODO
}

Note that the ms-appx:/// is the standard prefix for a uri to files within the application folder. If you want to get access to a file in your app data folder, just leave this off.

Add comment