不需要自訂提供者時,Windows 8 內建的 FileOpenPicker、FolderPicker、FileSavePicker 已能滿足多數檔案選取需求。它們提供一致的 Metro 風格 UI、支援縮圖/清單檢視、可指定起始位置與檔案類型過濾,且只需幾行非同步程式碼即可整合。本篇詳細示範三大選取器的核心屬性與實戰用法。
| 屬性 | 說明 |
|---|---|
ViewMode | PickerViewMode.List 或 Thumbnail,控制呈現模式 |
SuggestedStartLocation | PickerLocationId 列舉:PicturesLibrary、DocumentsLibrary、Desktop 等 |
FileTypeFilter | 允許顯示的副檔名集合,必須至少加入一項(可用 * 代表全部) |
CommitButtonText | 自訂確認按鈕文字(預設「開啟」) |
PickSingleFileAsync() | 單選模式,回傳 StorageFile 或 null(取消) |
PickMultipleFilesAsync() | 多選模式,回傳 IReadOnlyList<StorageFile> |
// 單選:挑選圖片
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.CommitButtonText = "選中此檔案";
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".gif");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null) lblMsg.Text = "選中檔案: " + file.Name;
else lblMsg.Text = "取消了";
// 多選:挑選文件
FileOpenPicker openPicker2 = new FileOpenPicker();
openPicker2.ViewMode = PickerViewMode.List;
openPicker2.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker2.FileTypeFilter.Add("*");
IReadOnlyList<StorageFile> files = await openPicker2.PickMultipleFilesAsync();
if (files.Count > 0) { /* 逐一處理 */ }
else lblMsg.Text = "取消了";
資料夾選取器僅支援單選 PickSingleFolderAsync(),回傳 StorageFolder。特殊在於 FileTypeFilter 這裡只是用來「過濾顯示哪些檔案類型」,使用者仍只能選資料夾而非檔案。
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add(".docx");
folderPicker.FileTypeFilter.Add(".xlsx");
folderPicker.FileTypeFilter.Add(".pptx");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null) lblMsg.Text = "選中資料夾: " + folder.Name;
else lblMsg.Text = "取消了";
| 屬性 | 說明 |
|---|---|
SuggestedStartLocation | 建議起始儲存位置 |
SuggestedFileName | 預設檔名(不含路徑) |
FileTypeChoices | IDictionary<string, IList<string>>,鍵為顯示名稱(如「文字檔」),值為副檔名清單 |
DefaultFileExtension | 預設副檔名 |
PickSaveFileAsync() | 彈出儲存對話框,回傳可寫入的 StorageFile |
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("文字檔", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "webabcdFileSavePicker";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// 1. 告訴系統暫緩其他程式更新此檔
CachedFileManager.DeferUpdates(file);
// 2. 寫入內容
string textContent = "I am webabcd";
await FileIO.WriteTextAsync(file, textContent);
// 3. 完成更新,讓系統處理版本衝突等
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
lblMsg.Text = (status == FileUpdateStatus.Complete)
? "檔案 " + file.Name + " 儲存成功"
: "儲存狀態: " + status;
}
else lblMsg.Text = "取消了";
XamlDemo.Common.Helper.EnsureUnsnapped() 確保不在 Snap 檢視模式下才開啟選取器,避免例外。FileTypeFilter 至少一項:否則會擲出例外;若不限類型請加 *。CompleteUpdatesAsync:確保檔案實際寫入磁碟並處理版本衝突。