Windows Phone8開發入門(四)




Windows Phone 8文件和存儲


 


WP7.1 IsolatedStorageIsolatedStorageSetting APIs


 


“本地存儲”和“獨立存儲”


讀取文件的不同方式:


Local Database data context


Files acess using WP7.1 Isolated Storage API


Files access using Windows.Storage API via URIs


File access using Windows.Storage API via StorageFolder references


WP8文件訪問的選擇:


//WP7.1 IsolatedStorage APIs


Var isf=IsolatedStorageFile.GetUserStoreForApplication();


IsolatedStorageFileStream fs=newIsolatedStorageFileStream("CaptainsLog.store",FileMode.Open,isf));


···


//WP8 Storage APIs using URI


StorageFile StorageFile=awaitWindowsd.Storage.StorageFile.GetFileFromApplicationUriAsync(newUri("ms-appdata:///local/CaptainsLog.store"));


```


//WP8 Storage APIs


Windows.Storage.StorageFolderlocalFolder=Windows.Storage.ApplicationData.Current.LocalFolder;


Windows.Storage.StorageFile storageFile=awaitlocalFolder.GetFileAsync("CaptainsLog.store");


```


使用WP7.1獨立存儲API保存數據


Isolated Storage Classes


IsolatedStorageFile


IsolatedFileStream


IsolatedStorageSettings


Saving Data


Private void saveGameToIsolatedStorage(string message)


{


Using(isolatedStorageFileisf=IsolatedStorageFile.GetUserStoreForApplication())


{


Using(IsolatedStorageFileSytreamrawStream=isf.CreaqteFile("MyFile.store"))


{


StreamWriter writer=new StreamWriter(rawStream);


Writer.WriteLine(message);      //save the message


Writer.Close();


}


}


 


Loading Data


Private String loadString()


{


String result=null;


Using(IsolatedStorageFileisf=IsolostedStorageFile.GetUserStoreForApplication())


{


If(isf.FileExists("Myfile.store")


{


Using(IsolatedStorageFileStreamrawStream=isf.OpenFile(filename,System.IO.FileMode.Open())


{


StreamReader  reader=newStreamReader(rawStream);


Result=reader.ReadLine();


Reader.Close();


}


}


}


Return result;


}


在應用設備中保存數據


Void saveString(streing message,string name)


{


IsolatedStorageSettings.ApplicationSettings[name]=message;


IsolatedStorageSettings.ApplicationSettings.Save();


 


 


使用設置存儲


使用StorageFolder保存數據


Using System.IO;


Using Windows.Storage;


```


Private async void saveToLocalFolderAsync(string message)


{


//Get a reference to the Local Folder


StorageFolder localFolder=ApplicationData.Current.LocalFolder;


//Create the file in the local folder, or if it already exists, justopen it


StorageFile storageFile=await storageFile.OpenStreamForWreteAsync();


Using(StreamWriter writer=new StreamWriter(writeStream))


{


Await writer.WriteAsync(logData);


}


}


使用ms-appdata:///local/or ms-appx:///訪問文件


//There's no FileExists method in WinRT, so have to try to open itand catch exception instead


StorageFile storageFile=null;


Bool fileExists=false;


Try


{


//Try to open file using URI


storageFile=await StorageFile.GetFileFromApplicationUriAsync(


NewUri("ms-appdata:///local/Myfile,store")


fileExists=true;


}


Catch(FileNotFoundException)


{


fileExists=false;


}


If(!fileExists)


{


AwaitApplicationData.Current.LoaclFolder.CreateFileAsync("Myfile.store",CreationCollisionOption.FaqilIfExists);


}


```


 


Windows.comStorageWindowsPhoneRunting)編程


Windows Phone8Windows8兼容性


Windows8中您可以以編程的方式加載應用程序包中的圖像文件,將圖像加載至XAML<Image>元素,代碼如下:


RecipeImage.Source=new System.Windows.Media.Imaging.BitmapImage(newUri(@"ms-appx:///Images/french/French_1_600_C.jpg",UriKind.RelativeOrAbsolute));


WindowsPhone8中不能使用這樣的URI語法,只能使用WindowsPhone OS7.1中的相對路徑,代碼如下:


RecipeImage.Source=newSystem.Windows.Media.Imgine.BitmapImage("/Images/french/French_1_600_C.jpg");


 


特殊文件夾


Shared/Media專輯封面


Shared/ShellContent圖塊


Shared/Transfers後臺文件傳輸


數據的序列化和反序列化(將對象集合的屬性寫入文件以便永久保存)


->Deactivated/Closig->Not running->Launching->Running


使用DataContractSerializer實現序列化


Public class MyDataSerializer<TheDataType>


{


Public static async Task SaveObjectsAsync(TheDataTypesourceData,String targetFileName)


{


StorageFile file=await|ApplicationData.Current.LocalFolder.CreateFileAsync(


targertFileName,CreationCollisionOpetion.ReplaceExisting);


Var outStream=await file.OpenStreamForWriteAsync();


DataContractSerializer serializer=newDataContractSerizlizer(typeof(TheDataType));


Serializer.WriteObject(outStream,sourceData);


Await outStream.FlushAsync();


outStream.Close();


}


```


}


使用DataContractSerializer實現反序列化


Puboic class MyDataSerializer<TheDataType>


{


Public static async Task<TheDataType>RestoreObjectsAsync(string fileName)


{


StorageFile file=awaitApplicationData.Current.LocalFolder.GetFileAsync(fileName);


Var inStream=await file.OpenstreamForReadAsync();


//Deserialize the objects.


DataContractSerializer serializer=newDataContractSerializer(typeof(TheDataType));


TheDataType data=(TheDataType)serializer.ReadObject(inStream);


inStream.Close();


Return data;


}


````


}


 


使用獨立存儲資源管理器ISETool.exe


語法:


Ts-Take snapshot


Re-Restore snapshot


Dir-lists the files or dirextories


 


使用可移動的SD


外部存儲(SD)卡(Windows Phone8 支持使用SD卡)


<Extensions>


<FileTypeAssociation Name="foo"TaskID="_default" NavUriFragment="fileToken=%s">


<SupportedFileTypes>


<FileTypeContentType="application/foo">.foo</FileType>


</SupportedFileTypes>


</FileTypeAssociation>


</Extensions>


WMAppMainifest.xml中聲明文件關聯


<Extensions>


<FileTypeAssociation Name="foo"TaskID="_default" NavUriFragment="fileToken=%s">


<SupportedFileTypes>


<FileTypeContentType="application/foo">.foo</FileType>


</SupportedFileTypes>


</FileTypeAssociation>


</Extensions>


最佳方法:


配額管理


Serialization and Threads


 


 


 


發佈了28 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章