Windows Phone 7 开发——独立存储

来源:互联网 发布:好听的网络名字女生 编辑:程序博客网 时间:2024/05/29 07:17
什么是独立存储?

独立存储不是一个新概念。在Silverlight 2中已经在使用了。本质上说这是一种在本地文件系统中存储数据或文件的方式。“独立(isolated)”是因为只有

你的程序才可以访问这些数据。如果你有两个应用程序,同时你想在它们之间共享数据的话,最好使用一些类似基于云的可以让你共享数据的服务。一个应用程

序不能共享,调用设备上其他的应用程序或与之进行交互。

有两种方式在本地存储你的数据。第一是通过库中的键/值对,叫做IsolatedStorageSettings。第二是通过创建真实的文件和目录,叫做IsolatedStorageFile。

IsolatedStorageSettings:

有很多时候,这可能是你需要的唯一存储方式。IsolatedStorageSettings允许你在一个字典中存储键/值对(注意,无需任何设定),然后再读取出来。这些数据会一直保存着

,无论应用程序停止/启动,或者关机等等。除非你删除它,或者用户卸载你的应用程序,否则它一直存在。要记住的一点是 在它被添加到字典中之前你无法读取它。下面的例子是

在用户在你的程序中接收电子邮件更新时需要保存用户设定的代码。用了一个多选框允许用户选择,还有一个将此值保存到独立存储中的事件。

view plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
namespace Day15_IsolatedStorage
{
public partial class MainPage : PhoneApplicationPage
{

 

       IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("emailFlag"))
{

bool flag = (bool)settings["emailFlag"];

}

esle

{

settings.Add("emailFlag", false);

}

IsolatedStorageFile:

使用IsolatedStorageFile是一种让你可以在用户的设备中存储真实文件的机制。例子中,在一个子目录中创建了一个文本文件,并读取文件中的内容。

我们还可以创建和删除目录,子目录及文件。看起来有很多代码,但实际上非常简单。我们创建一个新的IsolatedStorageFile对象,并使用一个IsolatedStorageFileStream对象将它写入到驱动器中。代码中加入了注释,这样你可以更清楚地看到发生了什么。有两个事件处理程序,一个用来保存文件,另一个读取:

保存文件:

    IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
            fileStorage.CreateDirectory("ServerInfo");
            StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("ServerInfo\\\\newText.txt", FileMode.OpenOrCreate, fileStorage));
            fileWriter.WriteLine(
“这是我写入的内容”);
            fileWriter.Close();

读取文件:

            IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
            StreamReader fileReader = null;
            try
            {
                fileReader = new StreamReader(new IsolatedStorageFileStream("ServerInfo\\\\newText.txt", FileMode.Open , fileStorage));
                string strInfo = fileReader.ReadLine();
                fileReader.Close();
            }
            catch (Exception)
            {
                string strInfo="Need to create directory and the file first.";
            }

本文来自CSDN博客,转载请标明出处:
href="http://blog.csdn.net/porscheyin/archive/2010/11/11/6002373.aspx">http://blog.csdn.net/porscheyin/archive/2010/11/11/6002373.aspx






原创粉丝点击