WinRT文件系統
WinRT和蘋果的AppStore的新政策一樣,也是一個沙箱環境,應用程序獲得的權限十分有限。這雖然提高了程序的安全性,但是也妨礙了一些系統底層功能的開發,降低了用戶體驗。
WinRT中文件系統也被限制在了庫中,這是Windows 7首次引入的類似于我的文檔的目錄結構,可以管理用戶常用的文檔、圖片、音樂、視頻等。
目前只能訪問系統內置的幾個庫:文檔、音樂、圖片、視頻,自定義的庫我沒有找到訪問的方法。若想訪問其他文件需要使用FilePicker、FolderPick等對話框,后續再來測試。
以文檔庫為例,測試一下文件系統。
大多數文件系統的API都位于Windows.Storage命名空間:
1、枚舉目錄中的頂層目錄:
Windows.Storage.StorageFolder __doc = Windows.Storage.KnownFolders.DocumentsLibrary;
//枚舉目錄中的頂層目錄
foreach (Windows.Storage.StorageFolder __folder in await __doc.GetFoldersAsync())
{
this.txtFolder.Text += __folder.Name + "\n";
}
GetFoldersAsync()沒有遞歸的重載版本,若想要獲取所有子目錄,則需要寫一個遞歸函數。
2、枚舉目錄中的頂層文件:
foreach (Windows.Storage.StorageFile __file in await __doc.GetFilesAsync())
{
this.txtFile.Text += __file.Name + "\n";
}
同上GetFilesAsync()也沒有重載版本。
3、創建文件,若存在則覆蓋:
await __doc.CreateFileAsync("Test.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
4、創建目錄,若存在則覆蓋:
await __doc.CreateFolderAsync("Test", Windows.Storage.CreationCollisionOption.ReplaceExisting);
5、復制文件:
StorageFile __f = await __doc.GetFileAsync("Test.txt");
StorageFolder __fo = await __doc.GetFolderAsync("Test");
await __f.CopyAsync(__fo, "NewTest.txt", NameCollisionOption.ReplaceExisting);
await __f.CopyAndReplaceAsync(__f);
目錄沒有提供Copy方法,需要手動處理,先創建空目錄,然后遞歸創建子目錄、子文件。
6、重命名文件:
await __f.RenameAsync("NewTest.txt", NameCollisionOption.ReplaceExisting);
7、重命名目錄:
await __fo.RenameAsync("NewTest", NameCollisionOption.ReplaceExisting);
8、剪切文件:
await __f.MoveAsync(__fo, "NewTest.txt", NameCollisionOption.ReplaceExisting);
目錄沒有提供剪切方法,也需要手動處理。
9、向文件中寫入文本:
await FileIO.WriteTextAsync(__f, "寫入文本");
FileIO是一個靜態類,可以對指定文件進行操作。類似還有一個PathIO,針對指定絕對路徑的文件或目錄進行操作。
10、通過字節寫入文件:
IBuffer __buffer = GetBufferFromString("通過字節寫入");
await FileIO.WriteBufferAsync(__f, __buffer);
11、獲取文件流:
IRandomAccessStream __stream = await __f.OpenAsync(FileAccessMode.ReadWriteNoCopyOnWrite);
12、刪除文件,直接刪除,不放進回收站:
await __f.DeleteAsync(StorageDeleteOption.PermanentDelete);
13、刪除目錄,直接刪除,不放進回收站:
await __fo.DeleteAsync(StorageDeleteOption.PermanentDelete);
注意只能刪除空目錄,若目錄中還有子目錄或文件,則需要先刪除子文件,需要遞歸刪除。

浙公網安備 33010602011771號