Quickstart: Accessing files programmatically (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

Access files and folders that are in a location like a folder, library, device, or network location. You can also query the files and folders in a location by constructing file and folder queries.

Roadmap: How does this topic relate to others? See:

Prerequisites

Enumerate files and folders in a location

The following example uses the StorageFolder.GetFilesAsync method to get all the files in the PicturesLibrary and then lists the name of each file. Next, the example uses the GetFoldersAsync method to get all the folders in the PicturesLibrary and then lists the name of each folder.

//#include <ppltasks.h>
//#include <string>
//#include <memory>
using namespace Windows::Storage;
using namespace Platform::Collections;
using namespace concurrency;
using namespace std;

// Be sure to specify the Pictures Folder capability in the appxmanifext file.
StorageFolder^ picturesFolder = KnownFolders::PicturesLibrary;

// Use a shared_ptr so that the string stays in memory
// until the last task is complete.
auto outputString = make_shared<wstring>();
*outputString += L"Files:\n";

// Get a read-only vector of the file objects
// and pass it to the continuation. 
create_task(picturesFolder->GetFilesAsync())        
    // outputString is captured by value, which creates a copy 
    // of the shared_ptr and increments its reference count.
    .then ([outputString] (IVectorView<StorageFile^>^ files)
{        
    for ( unsigned int i = 0 ; i < files->Size; i++)
    {
        *outputString += files->GetAt(i)->Name->Data();
        *outputString += L"\n";
    }
})
    // We need to explicitly state the return type 
    // here: -> IAsyncOperation<...>
    .then([picturesFolder]() -> IAsyncOperation<IVectorView<StorageFolder^>^>^ 
{
    return picturesFolder->GetFoldersAsync();
})
    // Capture "this" to access m_OutputTextBlock from within the lambda.
    .then([this, outputString](IVectorView<StorageFolder^>^ folders)
{        
    *outputString += L"Folders:\n";

    for ( unsigned int i = 0; i < folders->Size; i++)
    {
        *outputString += folders->GetAt(i)->Name->Data();
        *outputString += L"\n";
    }

    // Assume m_OutputTextBlock is a TextBlock defined in the XAML.
    m_OutputTextBlock->Text = ref new String((*outputString).c_str());
});
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StringBuilder outputText = new StringBuilder();

IReadOnlyList<StorageFile> fileList = 
    await picturesFolder.GetFilesAsync();

outputText.AppendLine("Files:");
foreach (StorageFile file in fileList)
{
    outputText.Append(file.Name + "\n");
}

IReadOnlyList<StorageFolder> folderList = 
    await picturesFolder.GetFoldersAsync();

outputText.AppendLine("Folders:");
foreach (StorageFolder folder in folderList)
{
    outputText.Append(folder.DisplayName + "\n");
}
Dim picturesFolder As StorageFolder = KnownFolders.PicturesLibrary
Dim outputText As New StringBuilder

Dim fileList As IReadOnlyList(Of StorageFile) =
    Await picturesFolder.GetFilesAsync()

outputText.AppendLine("Files:")
For Each file As StorageFile In fileList

    outputText.Append(file.Name & vbLf)

Next file

Dim folderList As IReadOnlyList(Of StorageFolder) =
    Await picturesFolder.GetFoldersAsync()

outputText.AppendLine("Folders:")
For Each folder As StorageFolder In folderList

    outputText.Append(folder.DisplayName & vbLf)

Next folder

Note In C# or Visual Basic, remember to put the async keyword in the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.

Alternatively, you can use the GetItemsAsync method to get both the files and the folders in a particular location. The following example uses the GetItemsAsync method to get all files and folders in the PicturesLibrary. Then the example lists the name of each file or folder. If the item is a folder, the example appends "folder" to the name.

// See previous example for comments, namespace and #include info.
StorageFolder^ picturesFolder = KnownFolders::PicturesLibrary;
auto outputString = make_shared<wstring>();

create_task(picturesFolder->GetItemsAsync())        
    .then ([this, outputString] (IVectorView<IStorageItem^>^ items)
{        
    for ( unsigned int i = 0 ; i < items->Size; i++)
    {
        *outputString += items->GetAt(i)->Name->Data();
        if(items->GetAt(i)->IsOfType(StorageItemTypes::Folder))
        {
            *outputString += L"  folder\n";
        }
        else
        {
            *outputString += L"\n";
        }
        m_OutputTextBlock->Text = ref new String((*outputString).c_str());
    }
});
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StringBuilder outputText = new StringBuilder();

IReadOnlyList<IStorageItem> itemsList = 
    await picturesFolder.GetItemsAsync();

foreach (var item in itemsList)
{
    if (item is StorageFolder)
    {
        outputText.Append(item.Name + " folder\n");

    }
    else
    {
        outputText.Append(item.Name + "\n");

    }
}
Dim picturesFolder As StorageFolder = KnownFolders.PicturesLibrary
Dim outputText As New StringBuilder

Dim itemsList As IReadOnlyList(Of IStorageItem) =
    Await picturesFolder.GetItemsAsync()

For Each item In itemsList

    If TypeOf item Is StorageFolder Then

        outputText.Append(item.Name & " folder" & vbLf)

    Else

        outputText.Append(item.Name & vbLf)

    End If

Next item

Query files in a location and enumerate matching files

The following example gets the files in the PicturesLibrary and groups them by the month. The example creates a StorageFolderQueryResult object by calling StorageFolder.CreateFolderQuery and passing the CommonFolderQuery.GroupByMonth value to the method. Then the example calls StorageFolderQueryResult.GetFoldersAsync. The results of GetFoldersAsync are virtual folders (StorageFolder objects) that are based on the CommonFolderQuery value, with the files in the PicturesLibrary and its sub-folders grouped into the virtual folders.

//#include <ppltasks.h>
//#include <string>
//#include <memory>
using namespace Windows::Storage;
using namespace Windows::Storage::Search;
using namespace concurrency;
using namespace Platform::Collections;
using namespace Windows::Foundation::Collections;
using namespace std;

StorageFolder^ picturesFolder = KnownFolders::PicturesLibrary;

StorageFolderQueryResult^ queryResult = 
    picturesFolder->CreateFolderQuery(CommonFolderQuery::GroupByMonth);

// Use shared_ptr so that outputString remains in memory
// until the task completes, which is after the function goes out of scope.
auto outputString = std::make_shared<wstring>();

create_task( queryResult->GetFoldersAsync()).then([this, outputString] (IVectorView<StorageFolder^>^ view) 
{        
    for ( unsigned int i = 0; i < view->Size; i++)
    {
        create_task(view->GetAt(i)->GetFilesAsync()).then([this, i, view, outputString](IVectorView<StorageFile^>^ files)
        {
            *outputString += view->GetAt(i)->Name->Data();
            *outputString += L"(";
            *outputString += to_wstring(files->Size);
            *outputString += L")\r\n";
            for (unsigned int j = 0; j < files->Size; j++)
            {
                *outputString += L"     ";
                *outputString += files->GetAt(j)->Name->Data();
                *outputString += L"\r\n";
            }
        }).then([this, outputString]()
        {
            m_OutputTextBlock->Text = ref new String((*outputString).c_str());
        });
    }    
});
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;

StorageFolderQueryResult queryResult = 
    picturesFolder.CreateFolderQuery(CommonFolderQuery.GroupByMonth);

IReadOnlyList<StorageFolder> folderList = 
    await queryResult.GetFoldersAsync();

StringBuilder outputText = new StringBuilder();

foreach (StorageFolder folder in folderList)
{
    IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();

    // Print the month and number of files in this group.
    outputText.AppendLine(folder.Name + " (" + fileList.Count + ")");

    foreach (StorageFile file in fileList)
    {
        // Print the name of the file.
        outputText.AppendLine("   " + file.Name);
    }
}
Dim picturesFolder As StorageFolder = KnownFolders.PicturesLibrary
Dim outputText As New StringBuilder

Dim queryResult As StorageFolderQueryResult =
    picturesFolder.CreateFolderQuery(CommonFolderQuery.GroupByMonth)

Dim folderList As IReadOnlyList(Of StorageFolder) =
    Await queryResult.GetFoldersAsync()

For Each folder As StorageFolder In folderList

    Dim fileList As IReadOnlyList(Of StorageFile) =
        Await folder.GetFilesAsync()

    ' Print the month and number of files in this group.
    outputText.AppendLine(folder.Name & " (" & fileList.Count & ")")

    For Each file As StorageFile In fileList

        ' Print the name of the file.
        outputText.AppendLine("   " & file.Name)

    Next file

Next folder

Note In C# or Visual Basic, remember to put the async keyword in the method declaration of any method in which you use the await operator. For more information, see Quickstart: Calling asynchronous APIs in C# or Visual Basic.

The output of the example looks similar to the following.

February ‎2012 (2)
   MyImage3.png
   MyImage4.png
‎November ‎2011 (2)
   MyImage1.png
   MyImage2.png

Summary and next steps

To learn about reading and writing files, see Quickstart: Reading and writing a file and the File access sample. To learn about working with image files, see Quickstart: Image and ImageBrush, Quickstart: Imaging, and the XAML image sample.

To learn how to access files through the file picker, see Quickstart: Accessing files with file pickers.

Accessing data and files

Quickstart: Accessing files with file pickers

Quickstart: Reading and writing a file

File access and permissions

Programmatic file search sample

Folder enumeration sample

File access sample

XAML image sample

Reference

Windows.Storage.KnownFolders class

Windows.Storage.StorageFile class

Windows.Storage.StorageFolder class

Windows.Storage.StorageItemTypes enum

Windows.Storage.Search.CommonFolderQuery enum

Windows.Storage.Search.StorageFolderQueryResult class