[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();
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
結果:
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"));
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();
結果:
很簡單的測試
參考連結:
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: