您的位置:首页 > 其它

Windows Phone 7 开发 31 日谈——第15日:独立存储

2011-01-10 08:53 411 查看

Windows Phone 7 开发 31 日谈——第15日:独立存储

本文是“Windows Phone 7 开发 31 日谈”系列的第15日。

昨天,我们讨论了程序中的墓碑机制从而让程序看起来是可以在后台运行的。今天,我们来谈谈在电话中存储本地数据的一种非常棒的方法。使用独立存储。

什么是独立存储?

独立存储不是一个新概念。在Silverlight 2中已经在使用了。本质上说这是一种在本地文件系统中存储数据或文件的方式。“独立(isolated)”是因为只有你的程序才可以访问这些数据。如果你有两个应用程序,同时你想在它们之间共享数据的话,最好使用一些类似基于云的可以让你共享数据的服务。一个应用程序不能共享,调用设备上其他的应用程序或与之进行交互。

设置和文件

有两种方式在本地存储你的数据。第一是通过库中的键/值对,叫做IsolatedStorageSettings。第二是通过创建真实的文件和目录,叫做IsolatedStorageFile。下图简要介绍了这些(由MSDN提供),我会为每种方式提供一个深入的例子。

代码

using System.IO.IsolatedStorage;
using System.IO;

private void SaveButton_Click(object sender, RoutedEventArgs e)
{
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();

//Create new subdirectory
fileStorage.CreateDirectory("textFiles");

//Create a new StreamWriter, to write the file to the specified location.
StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("textFiles\\newText.txt", FileMode.OpenOrCreate, fileStorage));
//Write the contents of our TextBox to the file.
fileWriter.WriteLine(writeText.Text);
//Close the StreamWriter.
fileWriter.Close();
}

private void GetButton_Click(object sender, RoutedEventArgs e)
{
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new StreamReader
StreamReader fileReader = null;

try
{
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("textFiles\\newText.txt", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();

//Write the contents of the file to the TextBlock on the page.
viewText.Text = textFile;
fileReader.Close();
}
catch
{
//If they click the view button first, we need to handle the fact that the file hasn't been created yet.
viewText.Text = "Need to create directory and the file first.";
}
}离开程序时这多像一个迷人的魔术,再回来时,会再次载入文件(它还在那儿!)。
你都知道了。现在我们在Windows Phone 7中有两种存储机制可以用。IsolatedStorageSettings和IsolatedStorageFile。我很乐意听到你在程序中使用这两种存储结构的创新用法。请留言!

下载代码示例

这个例子将上面展示的代码融合到了一个项目中。





原文地址:http://www.jeffblankenburg.com/post/31-Days-of-Windows-Phone-7c-Day-15-Isolated-Storage.aspx

if ($ != jQuery) {
$ = jQuery.noConflict();
}




金山崟霸
关注 - 7
粉丝 - 77

关注博主
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: