列舉和查詢檔案和資料夾
存取位於資料夾、媒體櫃、裝置或網路位置中的檔案和資料夾。 您也可以建構檔案和資料夾查詢,以查詢位置中的檔案和資料夾。
如需如何儲存通用 Windows 平台應用程式資料的指引,請參閱 ApplicationData 類別。
注意
如需完整範例,請參閱資料夾列舉範例。
必要條件
了解通用 Windows 平台 (UWP) 應用程式的非同步程式設計
您可以參閱在 C# 或 Visual Basic 中呼叫非同步 API,以了解如何在 C# 或 Visual Basic 中撰寫非同步應用程式。 若要了解如何使用 C++/WinRT 撰寫非同步應用程式,請參閱透過 C++/WinRT 的並行和非同步作業。 若要了解如何使用 C++/CX 撰寫非同步的應用程式,請參閱 C++/CX 的非同步程式設計。
位置的存取權限
例如,這些範例中的程式碼需要 picturesLibrary 功能,但您的位置可能需要不同的功能,或完全不需要任何功能。 若要深入了解,請參閱檔案存取權限。
列舉某個位置中的檔案和資料夾
注意
請記得宣告 picturesLibrary 功能。
在這個範例中,我們會先使用 StorageFolder.GetFilesAsync 方法來取得 KnownFolders.PicturesLibrary的根資料夾中 (不在子資料夾) 的所有檔案,並列出每個檔案的名稱。 接下來,我們會使用 StorageFolder.GetFoldersAsync 方法來取得 PicturesLibrary 中的所有子資料夾,並列出每個子資料夾的名稱。
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");
}
// MainPage.h
// In MainPage.xaml: <TextBlock x:Name="OutputTextBlock"/>
#include <winrt/Windows.Storage.h>
#include <sstream>
...
Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
{
// Be sure to specify the Pictures Folder capability in your Package.appxmanifest.
Windows::Storage::StorageFolder picturesFolder{
Windows::Storage::KnownFolders::PicturesLibrary()
};
std::wstringstream outputString;
outputString << L"Files:" << std::endl;
for (auto const& file : co_await picturesFolder.GetFilesAsync())
{
outputString << file.Name().c_str() << std::endl;
}
outputString << L"Folders:" << std::endl;
for (auto const& folder : co_await picturesFolder.GetFoldersAsync())
{
outputString << folder.Name().c_str() << std::endl;
}
OutputTextBlock().Text(outputString.str().c_str());
}
#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());
});
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
注意
在 C# 或 Visual Basic 中,請務必在您使用 await 運算子的任何方法的方法宣告中放置 async 關鍵字。
或者,您可以使用 StorageFolder.GetItemsAsync 方法取得特定位置中的所有項目 (檔案與子資料夾)。 下列範例使用 GetItemsAsync 方法取得 KnownFolders.PicturesLibrary 的根資料夾中 (不在子資料夾) 的所有檔案與子資料夾。 然後,該範例會列出每個檔案和子資料夾的名稱。 如果該項目是子資料夾,則該範例會將 "folder"
附加到名稱中。
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");
}
}
// MainPage.h
// In MainPage.xaml: <TextBlock x:Name="OutputTextBlock"/>
#include <winrt/Windows.Storage.h>
#include <sstream>
...
Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
{
// Be sure to specify the Pictures Folder capability in your Package.appxmanifest.
Windows::Storage::StorageFolder picturesFolder{
Windows::Storage::KnownFolders::PicturesLibrary()
};
std::wstringstream outputString;
for (Windows::Storage::IStorageItem const& item : co_await picturesFolder.GetItemsAsync())
{
outputString << item.Name().c_str();
if (item.IsOfType(Windows::Storage::StorageItemTypes::Folder))
{
outputString << L" folder" << std::endl;
}
else
{
outputString << std::endl;
}
OutputTextBlock().Text(outputString.str().c_str());
}
}
// 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());
}
});
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
查詢某個位置中的檔案並列舉相符的檔案
在這個範例中,我們會查詢依月份群組的 KnownFolders.PicturesLibrary 中的所有檔案,這次範例遞迴到子資料夾。 首先,我們會呼叫 StorageFolder.CreateFolderQuery,並將 CommonFolderQuery.GroupByMonth 值傳遞至該方法。 這會為我們提供一個 StorageFolderQueryResult 物件。
接下來,我們呼叫 StorageFolderQueryResult.GetFoldersAsync,其會傳回代表虛擬資料夾的 StorageFolder 物件。 在此案例中,我們會按月份分組,因此虛擬資料夾各代表一組具有相同月份的檔案。
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);
}
}
// MainPage.h
// In MainPage.xaml: <TextBlock x:Name="OutputTextBlock"/>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Storage.Search.h>
#include <sstream>
...
Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
{
// Be sure to specify the Pictures Folder capability in your Package.appxmanifest.
Windows::Storage::StorageFolder picturesFolder{
Windows::Storage::KnownFolders::PicturesLibrary()
};
Windows::Storage::Search::StorageFolderQueryResult queryResult{
picturesFolder.CreateFolderQuery(Windows::Storage::Search::CommonFolderQuery::GroupByMonth)
};
std::wstringstream outputString;
for (Windows::Storage::StorageFolder const& folder : co_await queryResult.GetFoldersAsync())
{
auto files{ co_await folder.GetFilesAsync() };
outputString << folder.Name().c_str() << L" (" << files.Size() << L")" << std::endl;
for (Windows::Storage::StorageFile const& file : files)
{
outputString << L" " << file.Name().c_str() << std::endl;
}
}
OutputTextBlock().Text(outputString.str().c_str());
}
#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());
});
}
});
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
該範例的輸出看起來類似以下內容。
July 2015 (2)
MyImage3.png
MyImage4.png
December 2014 (2)
MyImage1.png
MyImage2.png