Windows Phone 學習筆記 (6) – 存取檔案

Windows Phone - Storage

Windows Phone 對永久性資料的儲存方法。

Isolated Storage (隔離儲存區)

要對隔離儲存區做存取必須使用 IsolatedStorageFile 類別,使用前必須先取得該物件,如下:
IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
之後就可以使用 CreateDirectory 方法或是 CreateFile 方法的方式來建立目錄或是檔案。以及使用 StreamWriterStreamReader 來寫入或讀取檔案。 以下示範,將上面的文字框中的資料儲存到隔離儲存區,然後取出來在下面的文字框中顯示。程式碼如下:
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開啟的狀態下才會顯示資料,否則什麼也無法顯示。
本文網址:https://blog.tonycube.com/2012/06/windows-phone-6.html
Tony Blog 撰寫,請勿全文複製,轉載時請註明出處及連結,謝謝 😀

我要留言

留言小提醒:
1.回覆時間通常在晚上,如果太忙可能要等幾天。
2.請先瀏覽一下其他人的留言,也許有人問過同樣的問題。
3.程式碼請先將它編碼後再貼上。(線上編碼:http://bit.ly/1DL6yog)
4.文字請加上標點符號及斷行,難以閱讀者恕難回覆。
5.感謝您的留言,您的問題也可能幫助到其他有相同問題的人。