為了與Windows 8 的統一, Windows phone 8提供了新的檔案操作類型,新的檔案操作類型都包含在Windows.Storage命名空間中,其中包括StorageFolder,StorageFile,FileIO等類庫。Windwos.Storage組件中主要包含了IStorageFile和 IStorageFolder, 可以看出,一個是對檔案的操作,一個是對檔案夾的。
在正式版的SDK中,windows phone 7 通過
IsolatedStorageFile.GetUserStoreForApplication(); 查看私人變數 m_AppFilesPathAccess 可知
和 Windows phone 8 通過
await ApplicationData.Current.LocalFolder
擷取 的檔案目錄結構定義是一致的。都是
C:\Data\Users\DefApps\AppData\{ProductID}\Local
差異的是wp8對檔案操作基本都是基於非同步架構,而wp7主要是使用的是同步方法。
使用IStorageFile建立一個檔案
public void IStorageFileCreateFile(string fileName) { IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IAsyncOperation<StorageFile> iaStorageFile = applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); iaStorageFile.Completed = (IAsyncOperation<StorageFile> asyncInfo, AsyncStatus asyncStatus) => { if (asyncStatus == AsyncStatus.Completed) { } }; }
使用IStorageFile讀取一個檔案
public async Task<string> IStorageFileReadFile(string fileName) { string text; IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName); IRandomAccessStream accessStream = await storageFile.OpenReadAsync(); using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size)) { byte[] content = new byte[stream.Length]; await stream.ReadAsync(content, 0, (int)stream.Length); text = Encoding.UTF8.GetString(content, 0, content.Length); } return text; }