永久性資料的儲存方法。
(本文同步發表於 http://blog.tonycube.com )
永久性資料的儲存方法。
§ Isolated Storage (隔離儲存區)
Winodows Phone 將檔案的儲存放在 Isolated Storage (隔離儲存區) 中,隔離的意思就是該區域只有該 App 能夠存取,其他的 App 無法存取。目前官方沒有明確說明每個 App 能夠使用的隔離儲存區的空間大小。 要對隔離儲存區做存取必須使用 IsolatedStorageFile 類別,使用前必須先取得該物件,如下:
IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
之後就可以使用 CreateDirectory 方法或是 CreateFile 方法的方式來建立目錄或是檔案。以及使用 StreamWriter 及 StreamReader 來寫入或讀取檔案。
以下示範,將上面的文字框中的資料儲存到隔離儲存區,然後取出來在下面的文字框中顯示。程式碼如下:
private void btnSave_Click(object sender, RoutedEventArgs e) { IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream isoStream = isoFile.CreateFile("data.txt"); System.IO.StreamWriter writer = new System.IO.StreamWriter(isoStream); writer.WriteLine(txtInput.Text); writer.Close(); writer.Dispose(); } private void btnLoad_Click(object sender, RoutedEventArgs e) { IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication(); if (isofile.FileExists("/data.txt")) { StreamReader reader = new StreamReader(isofile.OpenFile("/data.txt", FileMode.Open), System.Text.Encoding.UTF8); string data = reader.ReadLine(); reader.Close(); reader.Dispose(); isofile.Dispose(); txtOutput.Text = data; } }
§ 查看隔離儲存區的工具
VS 開發工具沒有內建觀看隔離儲存區中檔案的工具,那我們怎麼知道檔案是否真的存在呢?必須到 CodePlex 去下載 Windows Phone 7 Isolated Storage Explorer,這個工具的功能很簡單,就只能查看 App 的隔離儲存區中的檔案。 要開啟它可以從兩個地方,一個是從開始功能表中去開啟;另一個是從 VS 中「檢視 -> 其他視窗」中去開啟。此外,必須是在模擬器中App開啟的狀態下才會顯示資料,否則什麼也無法顯示。