Search code examples
c#windows-runtimewindows-store-appswinrt-xaml.net-4.5

Create sub folders in My Pictures from Windows Store application


I'm trying to create a folder structure within My Pictures folder from a Windows store app. But I can't seem to get pass the first level.

I create my first level folder using the following code:

IAsyncOperation<StorageFolder> appFolder = Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync("AppPhotos");

if (appFolder==null)
{
    //Create folder
    appFolder = Windows.Storage.KnownFolders.PicturesLibrary.CreateFolderAsync("AppPhotos");
}

Now I want to create another folder below this call Level1.

I was expecting to be able to do the following:

appFolder.CreateFolderAsync("Level1");

But I don't have a CreateFolderAsync method from my appFolder.

So, how can I create that Folder and then how would I then select it?

Thanks in advance

I'm using Visual Studio 2012, C#4.5, XAML and I'm writing a windows store app.


Solution

  • You seem to have missed the async/await revolution there and assume the operation to get a folder is a folder. This should work:

    var appFolder = await Windows.Storage.KnownFolders.PicturesLibrary.GetFolderAsync("AppPhotos");
    
    if (appFolder == null)
    {
        //Create folder
        appFolder = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFolderAsync("AppPhotos");
    }
    

    You also need to add the async keyword in the method signature wherever the above code is located and then also if your method returns a value of type T - change it to return Task<T>, so for method signature:

    private void MyMethod()
    

    you would change it to

    private async Task MyMethod()
    

    and if your current signature is

    private bool MyMethod()
    

    you would need to do

    private async Task<bool> MyMethod()
    

    Finally in that last case - you would need to also change your calls from

    var myValue = MyMethod();
    

    to

    var myValue = await MyMethod();
    

    etc. marking all methods that make calls that await other methods with the async keyword.