[UWP] Windows.Storage StorageFolder & FileIO 寫入文字讀取文字

2015-09-01


最近在看 Universal Windows Platform 的東西,之前都是用isolated storage ,但是最近看到官方文件寫到



Isolated storage is not available for Windows Store apps. Instead, use the application data classes in the Windows.Storagenamespaces included in the Windows Runtime API to store local data and files. For more information, see Application data in the Windows Dev Center.



所以就乾脆改變紀錄的方法,其實,透過Windows.Storage他存放的位置跟之前Isolated Storage 位置差不多 基本上只是多一層,目前我測試位置是



C:\Users\[USERNAME]\AppData\Local\Packages\[APPID]\LocalState\


1.顯示App Storage 寫入路徑


Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
 
//顯示路徑
var dialog = new MessageDialog(localFolder.Path);
await dialog.ShowAsync();


結果:
Image 111

2.建立檔案夾




Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
 
//如果設定 CreationCollisionOption.OpenIfExists 如果原本沒有存在就會建立,如果存在就保持 而且 ErrorCode==null
//如果設定 CreationCollisionOption.FailIfExists 如果原本存在Status 會呈現 ErrorCode != null
var r = localFolder.CreateFolderAsync("data_pool", Windows.Storage.CreationCollisionOption.OpenIfExists);
 
 
//顯示結果
var dialog = new MessageDialog( (r.ErrorCode==null ).ToString());
await dialog.ShowAsync();

其中,比較重要的是 如果設定 CreationCollisionOption.OpenIfExists 如果原本沒有存在就會建立,如果具有該名稱的檔案或資料夾已經存在,則傳回現有的項目。 如果設定 CreationCollisionOption.FailIfExists 如果原本存在 ErrorCode 就不會是null

結果:
Image 112

3.寫入檔案


Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
 
var sf = await localFolder.CreateFileAsync(@"data_pool\t1.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sf, "許當麻" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));

此時開啟檔案夾就會看到 檔案出現了
Image 113

4.讀取檔案



var sf = await localFolder.GetFileAsync(@"data_pool\t1.txt");
var content = await Windows.Storage.FileIO.ReadTextAsync(sf);
 
//顯示結果
var dialog = new MessageDialog(content);
await dialog.ShowAsync();

結果:
Image 114

很簡單的測試
參考連結:
https://msdn.microsoft.com/zh-tw/library/windows/apps/windows.storage.creationcollisionoption
https://msdn.microsoft.com/en-us/library/3ak841sy.aspx
https://msdn.microsoft.com/zh-tw/library/windows/apps/xaml/hh700361.aspx

Source Code:


當麻許的超技八 2014 | Donma Hsu Design.