浅谈Isolated storage的应用 - [WP开发]

当一个WP应用程序安装好后,它会产生与访问多种类型的数据,包括一些即时数据(例如运行时的某些变量等),也会有一些长久保留持有的数据(例如程序的设置信息等)。在WP编程中,保存与访问即时数据有多种方式,例如可以通过PhoneApplicationService类的State属性来存储一些临时数据,由于WP编程中的墓碑机制,这些数据会保留直到用户主动删除或者当这个WP程序退出终止时。而为了保存持久性数据,在WP中我们可以通过使用isolated storage存储方式保存在本地磁盘上。

一、isolated storage 小览

在使用isolated storage前,我们需要引用System.IO.IsolatedStorage命名空间,专属某个程序的isolated storage区域内的所有文件该程序都可以访问与修改。如果我们只是想保留WP程序的一些配置信息的话,WP提供IsolatedStorageSettings这个类更为方便我们的操作。(ps.说到WP程序的配置信息,一种合理的设计方式应该是从整个应用程序的角度去看而不是单为某个页面保存设计信息。) 所以从全局的角度出发,与配置信息相关的操作应该与App这个类相关联。

 

二、IsolatedStorageSettings应用小例子

下面用一个小例子说明如何操作isolated storage。设计一个WP程序,其中有一个numTaps的变量存储即时数据,记录点击屏幕的次数,然后还有一个BackgroundBrush的变量作为配置信息存储该程序的背景颜色,也就是说该程序重新打开后的背景颜色不是初始化时的黑色,而是在加载时就载入了配置信息设置其背景颜色为保存时的颜色。

新建Windows Phone项目WPIsolatedStorage,然后在App类中定义一个公共变量BackgroundBrush,作为程序的配置信息。这时要思考什么时候应该保存这些配置信息,读取这些配置信息,WP程序部署后有5种状态:Launching、Running、Deactivated、Activated以及Closing。符合常理的情况应该是在Launching及Activated时加载入配置信息,而在Deactivated及Closing时保存配置信息。看到App.xaml.cs文件,该文件已经包含有PhoneApplicationService事件中的响应方法,我们只需要在这些方法体内实现逻辑功能保存及加载配置信息即可。

       private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            LoadSettings();
        }
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            LoadSettings();
        }
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
            SaveSettings();
        }
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
            SaveSettings();
        }

 

而LoadSettings()与SaveSetting()实现如下:

//Load setting and Save setting
        void LoadSettings()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            Color clr;
            if (settings.TryGetValue<Color>("backgroundColor", out clr))
                BackgroundBrush = new SolidColorBrush(clr);
        }

        void SaveSettings()
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (BackgroundBrush is SolidColorBrush)
            {
                settings["backgroundColor"] = (BackgroundBrush as SolidColorBrush).Color;
                settings.Save();
            }
        }


三、IsolatedStorageFile 应用小例子

从上面的代码中可以看出,IsolatedStorageSettings存储的是"键-值"对应关系型数据。其实WP的IsolatedStorage是一种类似Cookie的静态存储机制,可以将一些基本类型(String,Int)的信息甚至是自定义类型序列化后的静态存储于客户端文件中。独立存储[IsolatedStorage]是一个局部信任机制,当你创建一个WP应用程序时会在硬盘上创建相应独立的存储区域.这里面独立是相对于不同Windows Phone Project而言的. 当然如果应用程序中存在多个程序集[Project],那么存储空间在这多个程序集之间是共享的。第二部分的那个例子只是简单的介绍了IsolatedStorageSettings的应用,而在isolated storage中,IsolatedStorageFile也是有着很大的用处,用户可以通过它在独立存储中建立文件夹,建立文件,操作文件等。下面用一个例子来说明IsolatedStorageFile的用法。

先通过该程序在独立存储区域建立一个新文件夹及一个文本文件,并写入任意内容。然后退出该程序,重新进入这个程序,通过“读取内容”的按钮来获取独立存储区域内的文件内容。关键部分代码如下:

        IsolatedStorageFile storge;

        public MainPage()
        {
            InitializeComponent();
            storge = IsolatedStorageFile.GetUserStoreForApplication();
        }
        //在独立存储区域新建文件夹
        private void NewFolder_Click(object sender, RoutedEventArgs e)
        {
            storge.CreateDirectory("myFolder");
        }
        //在独立存储区域新建文件,并写入内容
        private void AddText_Click(object sender, RoutedEventArgs e)
        {
            StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream("myFolder\\file.txt",FileMode.OpenOrCreate,storge));
            //writer content
            writer.WriteLine("hello, windows phone");
            writer.Close();
        }
        //读取文件
        private void ReadText_Click(object sender, RoutedEventArgs e)
        {
            StreamReader reader = new StreamReader(new IsolatedStorageFileStream("myFolder\\file.txt", FileMode.Open, storge));
            string text = reader.ReadLine();
            txtblk.Text = text;
        }

下载代码


四、关于IsolatedStorage的七个Best Practice:

1、Wrap all calls to isolated storage within try/catch blocks to be resilient to potential IsolatedStorageExceptions, which can be thrown if isolated storage is disabled or if the store has been deleted.

把所有对Isolated Storage的调用都包裹在Try/Catch块中来捕获潜在的IsolatedStorageExceptions。因为导致异常的因素实在很多(禁用独立存储、独立存储空间不足、多个应用程序同时操作一份独立存储导致的不一致性,还有在某些情况下操作独立存储,可能会提示独立存储不可用)。

2、If your Silverlight application needs to store a lot of data in isolated storage, consider hosting it on its own site so that it won't affect other applications on the site and other applications won't affect it.

如果你的Silverlight应用程序需要独立存储很多的数据,最好把它放在一个单独的网站,这样就不会影响到其他的应用程序。因为所有放在同一网站下的Silverlight应用程序,使用的是同一定额,它们会互相挤占。

3、If you have a group of Silverlight applications that need to share data on the client, host them on the same site.

如果几个Silverlight应用程序需要在客户共享数据,把它们放在同一网站下。

4、Keep isolated storage paths as small as possible to prevent the internal full path from reaching the 260-character limit.

让独立存储的路径越小越好,避免路径长度达到260个字符的限制。

5、Encrypt sensitive data stored in isolated storage.

加密保存在Isolated Storage里的敏感数据,因为它们实际是文本文件,直接可读的。

6、Use IsolatedStorageSettings to store objects and simple settings in isolated storage.

使用IsolatedStorageSettings来储存对象和简单的设置。

7、Use IsolatedStorageFile if you want to use file and stream-based APIs, are storing large amounts of data, or need fine-grained control over the contents of isolated storage.

如果需要使用文件或者基于流的API,保存大数据,或者需要细粒度的控制独立存储中的内容,则使用IsolatedStorageFile。

 

出处-注意到这里的7个编程实践是针对Silverlight的,WP开发的时候要有所思考与灵活使用。

posted @ 2011-09-15 13:20  卿之  阅读(886)  评论(1编辑  收藏  举报
无觅相关文章插件,快速提升流量