Windows.Storage 不只提供檔案讀寫,更內建豐富的中繼資料查詢、縮圖產生、虛擬資料夾分組、Advanced Query Syntax (AQS) 全文搜尋等企業級功能。本篇將這些進階特性一一拆解並給出實戰範例。
BasicProperties props = await file.GetBasicPropertiesAsync();
lblMsg.Text = "Size: " + props.Size;
lblMsg.Text += " DateModified: " + props.DateModified;
var propertyNames = new List<string> { "System.DateAccessed", "System.DateCreated", "System.FileOwner" };
IDictionary<string, object> extra = await file.Properties.RetrievePropertiesAsync(propertyNames);
lblMsg.Text += " Owner: " + extra["System.FileOwner"];
完整屬性清單請參考 MSDN System Properties。
無需實體建立子資料夾,即可依月份、年份、評等等邏輯分組:
QueryOptions queryOptions = new QueryOptions(CommonFolderQuery.GroupByMonth);
StorageFolderQueryResult result = picturesFolder.CreateFolderQueryWithOptions(queryOptions);
IReadOnlyList<StorageFolder> virtualFolders = await result.GetFoldersAsync();
foreach (var monthFolder in virtualFolders)
{
IReadOnlyList<StorageFile> files = await monthFolder.GetFilesAsync();
// monthFolder.Name 為 "2024 年 1 月" 等格式
}
支援的分組類型:GroupByMonth、GroupByYear、GroupByRating、GroupByType 等。
查詢大量檔案時,預先指定需取得的屬性與縮圖,系統從 C:\Windows\Prefetch 讀取快取,大幅降低 I/O:
var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, new List<string> { ".jpg", ".png" });
// 預取影像屬性(寬高等)與自訂屬性
queryOptions.SetPropertyPrefetch(PropertyPrefetchOptions.ImageProperties,
new List<string> { "System.FileOwner" });
// 預取縮圖
queryOptions.SetThumbnailPrefetch(ThumbnailMode.PicturesView, 190, ThumbnailOptions.UseCurrentScale);
var queryResult = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();
// 後續存取 properties.Width、GetThumbnailAsync() 幾乎零延遲
ThumbnailMode mode = ThumbnailMode.PicturesView; // DocumentsView, VideosView, MusicView, ListView, SingleItem
uint requestedSize = 200;
ThumbnailOptions options = ThumbnailOptions.UseCurrentScale;
using (var thumbnail = await file.GetThumbnailAsync(mode, requestedSize, options))
{
if (thumbnail != null)
{
var bitmap = new BitmapImage();
bitmap.SetSource(thumbnail);
img.Source = bitmap;
// thumbnail.OriginalWidth/Height 為實際回傳尺寸
}
}
AQS 是 Windows 搜尋引擎的查詢語法,支援關鍵字、屬性限定、布林邏輯等:
var queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, new List<string> { "*" });
queryOptions.UserSearchFilter = "五月天"; // AQS 字串
var fileQuery = musicFolder.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> files = await fileQuery.GetFilesAsync();
| 語法 | 說明 | 範例 |
|---|---|---|
關鍵字 | 全文搜尋檔名、內容、標籤 | 五月天 |
property:value | 屬性限定 | author:王小明、datetaken:2024/01/01 |
kind:類型 | 檔案類別 | kind:music、kind:picture |
AND / OR / NOT | 布林邏輯 | 五月天 AND kind:music |
"" | 精確片語 | "擁抱" |