詳解Silverlight 2中的獨立存儲(Isolated Storage)

概述

獨立存儲(Isolated Storage)是Silverlight 2中提供的一個客戶端安全的存儲,它是一個與Cookie機制相似的局部信任機制。獨立存儲機制的APIs 提供了一個虛擬的文件系統和能夠訪問這個虛擬文件系統的數據流對象。Silverlight中的獨立存儲是基於 .NET Framework中的獨立存儲來創建的,因此它僅僅是.NET Framework中獨立存儲的一個子集。
Silverlight中的獨立存儲有如下一些特徵:
1.每一個基於Silverlight的應用程序都被分配了屬於它本身的一部分存儲空間, 可是應用程序中的程序集倒是在存儲空間中共享的。一個應用程序被服務器賦給了一個惟一的固定的標識值。基於Silverlight的應用程序的虛擬文件系統如今就以一個標識值的方式來訪問了。這個標識值必須是一個常量,這樣每次應用程序運行時才能夠找到這個共享的位置。  
2.獨立存儲的APIs 其實和其它的文件操做APIs相似,好比 File 和 Directory 這些用來訪問和維護文件或文件夾的類。 它們都是基於FileStream APIs 來維護文件的內容的。
3.獨立存儲嚴格的限制了應用程序能夠存儲的數據的大小,目前的上限是每一個應用程序爲1 MB。

使用獨立存儲

Silverlight中的獨立存儲功能經過密封類IsolatedStorageFile來提供,位於命名空間System.IO.IsolatedStorag中,IsolatedStorageFile類抽象了獨立存儲的虛擬文件系統。建立一個 IsolatedStorageFile 類的實例,可使用它對文件或文件夾進行列舉或管理。一樣還可使用該類的 IsolatedStorageFileStream 對象來管理文件內容,它的定義大概以下所示:
TerryLee_0072
在Silverlight 2中支持兩種方式的獨立存儲,即按應用程序存儲或者按站點存儲,能夠分別使用GetUserStoreForApplication方法和GetUserStoreForSite方法來獲取IsolatedStorageFile對象。下面看一個簡單的示例,最終的效果以下圖所示:
  TerryLee_0073
下面來看各個功能的實現:
建立目錄,直接使用CreateDirectory方法就能夠了,另外還可使用DirectoryExistes方法來判斷目錄是否已經存在:
void btnCreateDirectory_Click(object sender, RoutedEventArgs e)
{
    using (IsolatedStorageFile store =
                    IsolatedStorageFile.GetUserStoreForApplication())
    {
        String directoryName = this.txtDirectoryName.Text;
        if (this.lstDirectories.SelectedItem != null)
        {
            directoryName = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(),
                            directoryName);
        }
        if (!store.DirectoryExists(directoryName))
        {
            store.CreateDirectory(directoryName);
            HtmlPage.Window.Alert("建立目錄成功!");
        }
    }
}
建立文件,經過CreateFile方法來獲取一個IsolatedStorageFileStream,並將內容寫入到文件中:
void btnCreateFile_Click(object sender, RoutedEventArgs e)
{
    if (this.lstDirectories.SelectedItem == null &&
        this.txtDirectoryName.Text == "")
    {
        HtmlPage.Window.Alert("請先選擇一個目錄或者輸入目錄名");
        return;
    }
    using (IsolatedStorageFile store =
                       IsolatedStorageFile.GetUserStoreForApplication())
    {
        String filePath;
        if (this.lstDirectories.SelectedItem == null)
        {
            filePath = System.IO.Path.Combine(this.txtDirectoryName.Text,
                            this.txtFileName.Text + ".txt");
        }
        else
        {
            filePath = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(),
                            this.txtFileName.Text + ".txt");
        }
        
        IsolatedStorageFileStream fileStream = store.CreateFile(filePath);
        using (StreamWriter sw = new StreamWriter(fileStream))
        {
            sw.WriteLine(this.txtFileContent.Text);
        }
        fileStream.Close();
        HtmlPage.Window.Alert("寫入文件成功!");
    }
}
讀取文件,直接使用System.IO命名空間下的StreamReader:
void btnReadFile_Click(object sender, RoutedEventArgs e)
{
    if (this.lstDirectories.SelectedItem == null ||
        this.lstFiles.SelectedItem == null)
    {
        HtmlPage.Window.Alert("請先選擇目錄和文件!");
        return;
    }
    using (IsolatedStorageFile store =
                       IsolatedStorageFile.GetUserStoreForApplication())
    {
        String filePath = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(),
                          this.lstFiles.SelectedItem.ToString());
        if (store.FileExists(filePath))
        {
            StreamReader reader = new StreamReader(store.OpenFile(filePath,
                   FileMode.Open, FileAccess.Read));
            this.txtFileContent.Text = reader.ReadToEnd();
            this.txtDirectoryName.Text = this.lstDirectories.SelectedItem.ToString();
            this.txtFileName.Text = this.lstFiles.SelectedItem.ToString();
        }
    }
}
刪除目錄和文件:
void btnDeleteFile_Click(object sender, RoutedEventArgs e)
{
    if (this.lstDirectories.SelectedItem != null &&
       this.lstFiles.SelectedItem != null)
    {
        using (IsolatedStorageFile store =
                       IsolatedStorageFile.GetUserStoreForApplication())
        {
            String filePath = System.IO.Path.Combine(this.lstDirectories.SelectedItem.ToString(),
                    this.lstFiles.SelectedItem.ToString());
            store.DeleteFile(filePath);
            HtmlPage.Window.Alert("刪除文件成功!");
        }
    }
}
void btnDeleteDirectory_Click(object sender, RoutedEventArgs e)
{
    if (this.lstDirectories.SelectedItem != null)
    {
        using (IsolatedStorageFile store =
                       IsolatedStorageFile.GetUserStoreForApplication())
        {
            store.DeleteDirectory(this.lstDirectories.SelectedItem.ToString());
            HtmlPage.Window.Alert("刪除目錄成功!");
        }
    }
}
獲取目錄列表和文件列表:
void lstDirectories_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (lstDirectories.SelectedItem != null)
    {
        using (IsolatedStorageFile store =
                        IsolatedStorageFile.GetUserStoreForApplication())
        {
            String[] files = store.GetFileNames(
                this.lstDirectories.SelectedItem.ToString() + "/");
            this.lstFiles.ItemsSource = files;
        }
    }
}
void BindDirectories()
{
    using (IsolatedStorageFile store = 
                    IsolatedStorageFile.GetUserStoreForApplication())
    {
        String[] directories = store.GetDirectoryNames("*");
        this.lstDirectories.ItemsSource = directories;
    }
}

增長配額

在本文一開始我就提到獨立存儲嚴格的限制了應用程序能夠存儲的數據的大小,可是咱們能夠經過IsolatedStorageFile類提供的IncreaseQuotaTo方法來申請更大的存儲空間,空間的大小是用字節做爲單位來表示的,以下代碼片斷所示,申請獨立存儲空間增長到5M:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
    long newQuetaSize = 5242880;
    long curAvail = store.AvailableFreeSpace;
    if (curAvail < newQuetaSize)
    {
        store.IncreaseQuotaTo(newQuetaSize);
    }
}
當咱們試圖增長空間大小時瀏覽器將會彈出一個確認對話框,供咱們確認是否容許增長獨立存儲的空間大小。
TerryLee_0076 

文件被存往何處

既然獨立獨立存儲是存放在客戶端本地,那到底存放在何處呢?在我我的計算機上的地址爲:C:\Users\TerryLee\AppData\LocalLow\Microsoft\Silverlight\is\035kq51b.2q4\pksdhgue.3rx\1,不一樣機器會有一些變化,另外在XP下的存儲位置與Vista是不相同的。在g文件夾下面,咱們找到當前應用程序的一些公有信息,能夠看到有以下三個文件:
TerryLee_0074
id.dat記錄了當前應用程序的ID
quota.dat記錄了當前應用程序獨立存儲的配額,即存儲空間大小
used.dat記錄已經使用的空間
在另外一個s文件夾下能夠找到咱們建立的目錄以及文件,而且能夠打開文件來看到存儲的內容,以下圖所示:
TerryLee_0075

禁用獨立存儲

如今咱們來思考一個問題,既然獨立存儲是一個與Cookie機制相似的局部信任機制,咱們是否也能夠禁用獨立存儲呢?答案天然是確定的。在Silverlight應用程序上點擊右鍵時,選擇Silverlight Configuration菜單,將會看到以下窗口:
TerryLee_0077
在這裏咱們能夠看到每個應用程序存儲空間的大小以及當前使用的空間;能夠刪除應用程序獨立存儲數據或者禁用獨立存儲的功能。

獨立存儲配置

最後在簡單說一下獨立存儲配置,在Beta 1時代是應用程序配置,如今不只支持應用程序配置,同時還支持站點配置,咱們能夠用它來存儲應用程序配置如每一個頁面顯示的圖片數量,頁面佈局自定義配置等等,使用IsolatedStorageSettings類來實現,該類在設計時使用了字典來存儲名-值對,它的使用至關簡單:
IsolatedStorageSettings appSettings = 
    IsolatedStorageSettings.ApplicationSettings;
appSettings.Add("mykey","myValue");
appSettings.Save();
IsolatedStorageSettings siteSettings =
    IsolatedStorageSettings.SiteSettings;
siteSettings.Add("mykey1","myValue1");
siteSettings.Save();
獨立存儲配置的機制與咱們上面講的同樣,它也是基於本地文件存儲,系統默認的會建立一個名爲__LocalSettings的文件進行存儲,以下圖所示:
TerryLee_0078
打開文件後能夠看到,存儲的內容(此處進行了整理)
<ArrayOfKeyValueOfstringanyType 
  xmlns:i="[url]http://www.w3.org/2001/XMLSchema-instance[/url]"
  xmlns="[url]http://schemas.microsoft.com/2003/10/Serialization/Arrays[/url]">
  <KeyValueOfstringanyType>
    <Key>mykey</Key>
    <Value xmlns:d3p1="[url]http://www.w3.org/2001/XMLSchema[/url]" 
           i:type="d3p1:string">myValue</Value>
  </KeyValueOfstringanyType>
</ArrayOfKeyValueOfstringanyType>
值得一提的是使用獨立存儲配置不只僅能夠存儲簡單類型的數據,也能夠存儲咱們自定義類型的數據。

小結

本文詳細介紹了Silverlight 2中的獨立存儲機制,但願對你們有所幫助。
示例下載:

0javascript

收藏java

lihuijun

203篇文章,79W+人氣,0粉絲

Ctrl+Enter 發佈linux

發佈git

取消windows

3條評論瀏覽器

按時間倒序 按時間正序

0安全

3
分享
lihuijun

推薦專欄更多

帶你玩轉高可用

前百度高級工程師的架構高可用實戰

共15章 | 曹林華

¥51.00 524人訂閱
負載均衡高手煉成記

高併發架構之路

共15章 | sery

¥51.00 607人訂閱
基於Python的DevOps實戰

自動化運維開發新概念

共20章 | 撫琴煮酒

¥51.00 575人訂閱
網工2.0晉級攻略 ——零基礎入門Python/Ansible

網絡工程師2.0進階指南

共30章 | 薑汁啤酒

¥51.00 2076人訂閱
全局視角看大型園區網

路由交換+安全+無線+優化+運維

共40章 | 51CTOsummer

¥51.00 2641人訂閱

掃一掃,領取大禮包