獨立存儲, windows phone IsolatedStorageFile

 

獨立存儲

    獨立存儲機制是從Silverlight中提取出來的技術,最初的目的是爲Silverlight應用程序提供一個客戶端安全的存儲,在代碼與保存的數據之間定義了標準化的關聯機制,它是一個與Cookie機制類似的信任機制,可以爲數據提供很好的隔離性和安全性。而實際上,在Silverlight中,所有的I/O操作的處理都被視爲獨立存儲,不使用操作系統的文件系統。
    獨立存儲的API提供了一個虛擬的文件操作系統(IsolatedStorageFile),提供對存儲的程序和應用程序文件的基本管理,每一個IsolatedStorageFile的實例表示位於文件系統中的一個單獨存儲區。API還提供了數據流(IsolatedStorageFileStream)的操作用於存儲區的文件。使用者還可以使用IsolatedStorageScope枚舉值來創建並選擇具有適當隔離類 型的存儲區。

    在Windows Phone中繼續使用來自Silverlight的獨立存儲概念。區別只是在Windows Phone 中沒有文件大小的限制。

    在Windows Phone中,有關獨立存儲的操作主要使用的是位於System.IO.IsolatedStorage命名空間下的類:

  • IsolatedStorageFile(表示包含文件和目錄的獨立存儲區)
  • IsolatedStorageFileStream(流操作)
  • IsolatedStorageSettings(提供一個在獨立存儲中存儲數據的鍵值對)
  • IsolatedStorageException(獨立存儲中的操作失敗時引發的異常)

IsolatedStorageFile



IsolatedStorageFile表示包含文件和目錄的獨立存儲區,它用來獲得實例的方法不是使用構造函數,而是:

IsolatedStorageFile myIsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

我們通過使用它的一些屬性和方法來實現獨立存儲。

常用屬性:

  1. AvailableFreeSpace 獲取一個值,該值表示獨立存儲的可用空間量。
  2. IsEnabled 獲取一個值,該值指示是否啓用了獨立存儲。
  3. Quota 獲取一個值,該值表示獨立存儲的最大可用空間量。
  4. UsedSize 獲取一個值,該值表示用於獨立存儲的空間量。

常用方法:

  1. CopyFile,將現有文件複製到新文件,它有一個重載函數用來判斷是不是覆蓋現有文件,即CopyFile(String, String, Boolean)。
  2. CreateDirectory 在獨立存儲範圍中創建目錄。
  3. CreateFile 在獨立存儲區中創建文件。
  4. DeleteDirectory 刪除獨立存儲範圍中的目錄。
  5. DeleteFile 刪除獨立存儲區中的文件。
  6. DirectoryExists 確定指定的路徑是否指的是獨立存儲區中的現有目錄。
  7. Dispose 釋放由 IsolatedStorageFile 使用的所有資源。
  8. FileExists 確定指定的路徑是否指的是獨立存儲區中的現有文件。
  9. GetCreationTime 返回指定文件或目錄的創建日期和時間。
  10. GetDirectoryNames 枚舉獨立存儲區根處的目錄。
  11. GetDirectoryNames(String) 枚舉獨立存儲範圍中與給定模式匹配的目錄。
  12. GetFileNames 獲取獨立存儲區根處的文件的名稱。
  13. GetFileNames(String) 枚舉獨立存儲範圍中與給定模式匹配的文件。
  14. GetLastAccessTime 返回上次訪問指定文件或目錄的日期和時間。
  15. GetLastWriteTime 返回上次寫入指定文件或目錄的日期和時間。
  16. GetUserStoreForApplication 獲取從虛擬主機域調用的應用程序所使用的用戶範圍的獨立存儲。
  17. GetUserStoreForSite 獲取由虛擬主機域中的所有應用程序使用的某個用戶範圍的獨立存儲。
  18. IncreaseQuotaTo 使應用程序顯式請求一個更大的配額大小,以字節爲單位。
  19. MoveDirectory 將指定的目錄及其內容移到新位置。
  20. MoveFile 將指定文件移到新位置,還可以允許您指定新文件名。
  21. OpenFile,打開文件,配合流的操作進行文件的讀寫,不同的重載方法實現不同打開方式,有OpenFile(String, FileMode)(在指定的模式中打開文件)、OpenFile(String, FileMode, FileAccess) (以指定的文件訪問權限在指定的模式下打開文件)、OpenFile(String, FileMode, FileAccess, FileShare)(用讀、寫或讀/寫訪問權限和指定的共享選項在指定的模式中打開文件)
  22. Remove 移除獨立存儲區範圍及其所有內容。

IsolatedStorageFileStream

公開獨立存儲中的文件,使用流的方式來操作文件。獲取實例的方法:

IsolatedStorageFileStream myFileStream=myIsolatedStorageFile.OpenFile("content.txt",FileMode.OpenOrCreate,FileAccess.Write);

它可以配合StreamWriter與StreamReader來實現讀寫。

常用屬性:

  1. CanRead 已重寫。獲取一個布爾值,該值指示該文件是否可讀。
  2. CanSeek 已重寫。獲取一個布爾值,該值指示查找操作是否受支持。
  3. CanTimeout 獲取一個值,該值確定當前流是否可以超時。
  4. CanWrite 已重寫。獲取一個布爾值,該值指示是否可以寫入文件。
  5. Length 已重寫。獲取 IsolatedStorageFileStream 對象的長度。
  6. Name 獲取傳遞給構造函數的 FileStream 的名稱。
  7. Position 已重寫。獲取當前 IsolatedStorageFileStream 對象的當前位置或將該位置設置爲指定值。
  8. ReadTimeout 獲取或設置一個值,該值確定流在超時前嘗試讀取多長時間。 
  9. WriteTimeout 獲取或設置一個值,該值確定流在超時前嘗試寫入多長時間。

常用方法:

  1. BeginRead  開始異步讀。
  2. BeginWrite  開始異步寫。
  3. Close 關閉當前流並釋放與之關聯的所有資源(如套接字和文件句柄)。 (從 Stream 繼承。
  4. EndRead  結束掛起的異步讀取請求。
  5. EndWrite  結束異步寫入。
  6. Flush  用緩衝區的當前狀態更新文件,然後清除緩衝區。
  7. Read  將字節從當前緩衝的 IsolatedStorageFileStream 對象複製到數組。
  8. ReadByte  從獨立存儲中的 IsolatedStorageFileStream 對象讀取一個字節。
  9. Seek  將此 IsolatedStorageFileStream 對象的當前位置設置爲指定值。
  10. SetLength  將此 IsolatedStorageFileStream 對象的長度設置爲指定的 value。
  11. Write  使用從字節數組中讀取的數據將字節塊寫入 IsolatedStorageFileStream 對象。
  12. WriteByte  將一個字節寫入 IsolatedStorageFileStream 對象。


IsolatedStorageSettings

提供一個在獨立存儲中存儲鍵/值對的 Dictionary(Of TKey, TValue)。它就是存儲一個可供使用的數據的鍵值對,一般是比較少的數據,而使用IsolatedStorageFile來存儲的是以文件的形式存儲的數據,一般比較大。獲取實例的方法:

 private IsolatedStorageSettings myIsolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings;

常用屬性:

  1. ApplicationSettings 獲取一個 IsolatedStorageSettings 實例,該實例包含應用程序的應用程序級 IsolatedStorageFile 的內容;如果不存在這樣的實例,則創建一個新的 IsolatedStorageSettings 實例。
  2. Count 獲取存儲在字典中的鍵/值對的數目。
  3. Item 獲取或設置與指定的鍵相關聯的值。
  4. Keys 獲取包含詞典中的鍵的集合。
  5. SiteSettings 獲取一個 IsolatedStorageSettings 實例,該實例包含應用程序的域級 IsolatedStorageFile 的內容;如果不存在這樣的實例,則創建一個新的IsolatedStorageSettings 實例。
  6. Values 獲取包含詞典中的值的集合。 

常用方法:

  1. Add 將鍵/值對的對應項添加到字典中。
  2. Clear 將 IsolatedStorageSettings 中存儲的項的計數重置爲零,並釋放對集合中元素的所有引用。
  3. Contains 確定應用程序設置字典是否包含指定鍵。
  4. Remove 移除具有指定鍵的項。
  5. Save 保存寫入到當前 IsolatedStorageSettings 對象的數據。
  6. TryGetValue(Of T) 獲取指定鍵的值。

注意:一般的,在寫IsolatedStorageFile等的實例的時候,由於單詞IsolatedStorageFile 比較長,我們可以寫作var使系統區識別,這也算一個小技巧了。如:

var myIsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

下面是一個簡單地例子,我們使用一個簡單地qq登錄界面來說明問題,假設在用戶使用qq登錄功能的時候,因爲一些事情而離開了登錄界面,在不重啓手機的情況下,當用戶再次進入到qq登錄界面的時候,自動顯示出用戶之前填寫的用戶名和密碼(在這裏不考慮用戶是否有意願去顯示密碼,而且使用TextBox)。而在登錄界面中多寫一個TextBox來記錄用戶輸入的信息。

獨立存儲的具體實現:

  • 登錄賬號及密碼使用IsolatedStorageSetting來實現
  • 信息記錄使用IsolatedStorageFile來實現 

 特別的,在App.xaml.cs這個全局性的文件中定義方法SaveToFile來實現數據保存,定義方法ReadFromFile來實現數據讀取,在每次關閉的時候調用SaveToFile函數在方法Application_Deactivated與Application_Closing方法中使用SaveToFile,在Application_Activated方法和Application_Launching方法中使用ReadFromFile。另外:

在App.xaml.cs中的這四個重要的方法(app可以理解爲繼承自Application類的子類):

Application_Launching,應用程序啓動(例如,從“開始”菜單啓動)時執行的代碼,此代碼在重新激活應用程序時不執行。

Application_Activated, 激活應用程序(置於前臺)時執行的代碼,此代碼在首次啓動應用程序時不執行。

Application_Deactivated,停用應用程序(發送到後臺)時執行的代碼,此代碼在應用程序關閉時不執行。

Application_Closing,應用程序關閉(例如,用戶點擊“後退”)時執行的代碼,此代碼在停用應用程序時不執行。

具體過程:

1.在頁面中添加三個TextBlock來進行標籤性的說明,三個TextBox來使用戶輸入信息。佈局如圖:


<!--ContentPanel - 在此處放置其他內容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Height="54" HorizontalAlignment="Left" 
                       Margin="30,55,0,0" Name="textBlock1" 
                       Text="姓名:" VerticalAlignment="Top" 
                       FontSize="32" Width="96" />
            <TextBlock Height="54" HorizontalAlignment="Left" 
                       Margin="30,130,0,0" Name="textBlock2" 
                       Text="密碼:" VerticalAlignment="Top" 
                       FontSize="32"/>
            <TextBlock Height="54" HorizontalAlignment="Left" 
                       Margin="30,277,0,0" Name="textBlock4" 
                       Text="信息:" VerticalAlignment="Top" 
                       FontSize="32"/>
            <TextBox Height="72" HorizontalAlignment="Left" 
                     Margin="115,37,0,0" Name="userName" 
                     Text="" VerticalAlignment="Top" Width="307" 
                     TextChanged="userName1_TextChanged"/>
            <TextBox Height="72" HorizontalAlignment="Left" 
                     Margin="115,112,0,0" Name="password" 
                     Text="" VerticalAlignment="Top" Width="307" 
                     TextChanged="password1_TextChanged"/>
            <TextBox HorizontalAlignment="Left" 
                     Margin="115,277,0,36" Name="myInfo" 
                     Text="" Width="307" TextWrapping="Wrap"
                     TextChanged="myInfo_TextChanged"/>
        </Grid>

2.獲取IsolatedStorageSetting的實例,並添加每個TextBox的TextChanged事件。

private IsolatedStorageSettings myIsolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings;//獲取IsolatedStorageSettings實例
 private void userName1_TextChanged(object sender, TextChangedEventArgs e)
        {
            myIsolatedStorageSettings["userName"] = this.userName.Text.ToString();
        }

        private void password1_TextChanged(object sender, TextChangedEventArgs e)
        {
            myIsolatedStorageSettings["password"] = this.password.Text.ToString();
        }
3.添加頁面的讀取PhoneApplicationPage_Loaded事件。
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            string userName1 = "";
            string password1 = "";
            if (myIsolatedStorageSettings.Contains("userName"))
            {
                if (myIsolatedStorageSettings.TryGetValue<string>("userName", out userName1))//說明獲取了userName1
                {
                   this.userName.Text=userName1;
                }
            }
            if (myIsolatedStorageSettings.Contains("password"))
            {
                if (myIsolatedStorageSettings.TryGetValue<string>("password", out password1))//說明獲取了userName1
                {
                    this.password.Text = password1;
                }
            }
        }
4.在App.xaml.cs中添加兩個方法,分別實現存儲和讀取。另外添加一個string,來存儲共享數據。
public string Content { set; get; }
        public void SaveToFile() 
        {
            using (IsolatedStorageFile myIsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!myIsolatedStorageFile.DirectoryExists("MyFolder"))//如果不存在文件夾“MyFolder”
                {
                    myIsolatedStorageFile.CreateDirectory("MyFolder");//創建文件夾
                }
                using(IsolatedStorageFileStream myFileStream=myIsolatedStorageFile.OpenFile("MyFolder\\content.txt",FileMode.OpenOrCreate,FileAccess.Write))
                {
                    using (StreamWriter myWriter = new StreamWriter(myFileStream))
                    {
                        myWriter.WriteLine(Content);
                    }
                }
            }
        }
        public void ReadFromFile()
        {
            using (IsolatedStorageFile myIsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!myIsolatedStorageFile.DirectoryExists("MyFolder"))//如果不存在文件夾“MyFolder”
                {
                    myIsolatedStorageFile.CreateDirectory("MyFolder");//創建文件夾
                }
                if (myIsolatedStorageFile.FileExists("MyFolder\\content.txt"))
                {
                    using (IsolatedStorageFileStream myFileStream = myIsolatedStorageFile.OpenFile("MyFolder\\content.txt", FileMode.Open, FileAccess.Read))
                    {
                        using (StreamReader myReader = new StreamReader(myFileStream))
                        {
                            while (myReader.Peek() > 0)//判斷是不是到了尾部
                            {
                                 Content=myReader.ReadToEnd();
                            }
                        }
                    }
                }
            }  
        }

5.在Application_Deactivated與Application_Closing方法中添加SaveToFile方法,在Application_Activated方法和Application_Launching方法中添加ReadFromFile方法。

// 應用程序啓動(例如,從“開始”菜單啓動)時執行的代碼
        // 此代碼在重新激活應用程序時不執行
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            ReadFromFile();
        }

        // 激活應用程序(置於前臺)時執行的代碼
        // 此代碼在首次啓動應用程序時不執行
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            ReadFromFile();
        }

        // 停用應用程序(發送到後臺)時執行的代碼
        // 此代碼在應用程序關閉時不執行
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
            SaveToFile();
        }

        // 應用程序關閉(例如,用戶點擊“後退”)時執行的代碼
        // 此代碼在停用應用程序時不執行
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
            SaveToFile();
        }
6.在MainPage.xaml.cs中構建這樣的代碼:

 

private string myContent;// 構造函數
        public MainPage()
        {
            InitializeComponent();

            LoadContent();
        }

        private void LoadContent()
        {
            (Application.Current as App).ReadFromFile();
            myContent=(Application.Current as App).Content;
            if (myContent != "")
            {
                this.myInfo.Text = myContent;
            }
        }

最後在Application_Load事件中添加LoadContent方法的調用。最後的執行效果:

 關閉或退出後重新進入之後:

 


轉載於

http://www.cnblogs.com/waitingsky/archive/2012/04/14/wp7IsolatedStorage.html 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章