Windows 8.1 Storage API

This post covers the Windows 8.1/Windows Phone 8.1 Storage API.

Relevant namespaces for all snippets

using System.IO;
using Windows.Storage;
using Windows.Storage.Streams;

Get StorageFolder from local application package

var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");

Convert IRandomAccessStream into a Stream

using(IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
using(var stream = fileStream.AsStream())
{
    ....
}

Get a storage folder from a path with multiple parts:

relativePath could be folderA/folderB/…

public async Task<IStorageFolder> GetStorageFolderFromPath(
                                        IStorageFolder folder,
                                        string relativePath
                                  )
{
    var parts = relativePath.Split(Path.AltDirectorySeparatorChar,
                    Path.DirectorySeparatorChar);

    foreach (var part in parts)
    {
        folder = await folder.GetFolderAsync(part);
    }

    return folder;
}

Extension methods for copying StorageFolder shallow or recursively

/// <summary>
/// Recursive copy of files and folders from source to destination.
/// </summary>
public static async Task CopyContentsRecursive(this IStorageFolder source, IStorageFolder dest)
{
    await CopyContentsShallow(source, dest);

    var subfolders = await source.GetFoldersAsync();
    foreach (var storageFolder in subfolders)
    {
        await storageFolder.CopyContentsRecursive(await dest.GetFolderAsync(storageFolder.Name));
    }
}

/// <summary>
/// Shallow copy of files and folders from source to destination.
/// </summary>
public static async Task CopyContentsShallow(this IStorageFolder source, IStorageFolder destination)
{
    await source.CopyFiles(destination);

    var items = await source.GetFoldersAsync();

    foreach (var storageFolder in items)
    {
        await destination.CreateFolderAsync(storageFolder.Name, CreationCollisionOption.ReplaceExisting);
    }
}

/// <summary>
/// Copy files from source into destination folder.
/// </summary>
private static async Task CopyFiles(this IStorageFolder source, IStorageFolder destination)
{
    var items = await source.GetFilesAsync();

    foreach (var storageFile in items)
    {
        await storageFile.CopyAsync(destination, storageFile.Name, NameCollisionOption.ReplaceExisting);
    }
}   

 

Create a BitmapImage from a storage file

The following code will create a BitmapImage from a storage file:

public async Task<BitmapSource> GetBitmapImage(IStorageFolder baseFolder, string name)
{
    var file = await baseFolder.GetFileAsync(name);

    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
    {
        var image = new BitmapImage();

        using (var stream = fileStream.AsStreamForRead())
            image.SetSource(stream);

        return image;
    }
}