您的位置:首页 > 其它

WP7的独立存储

2012-11-19 11:31 225 查看
最近在做一个Windows phone 7上的客户端程序,较为简单,接触了WP7的一些东西,稍作笔记。WP7上的开发,是silverlght的又一次推广,所以入手容易,开发出来的效果也会很华丽。由Visual Studio、Expression Blend的强大支持,开发效率也会很高。本篇记叙下WP7的存储方式-独立存储。在参与的项目中,是用于保存用户添加的应用。

      WP7 没有本地数据库API可以利用,提供的有XML、独立存储和云存储。Isolated Storage[独立存储]有两种方式在本地存储你的数据。第一是通过库中的键/值对,叫做IsolatedStorageSettings。第二是通过创建真实的文件和目录,叫做IsolatedStorageFile

      IsolatedStorageSettings:

[c-sharp] view
plaincopy

/*使用 ApplicationSettings 属性可创建用于在独立存储中存储键/值对的字典的新实例. 

 * ApplicationSettings 特定于某个用户和某个应用程序。 

 */  

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;  

//添加键值对  

settings.Add("flag", false);  

//读取键值对  

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

//设置键值对  

settings["flag"] = true;  

//判断某键是否存在  

bool isExist = settings.Contains("flag");  

 

      IsolatedStorageFile:

[c-sharp] view
plaincopy

 using System.IO.IsolatedStorage;  

 //为程序获取一个虚拟的本地存储  

 IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();  

 //创建一个新的文件夹  

 fileStorage.CreateDirectory("textFiles");  

 /* 建立文件流,参数分别为:文件路径、打开模式、存储区。 

  * 打开模式有 

  * FileMode.Append-Opens the file if it exists and seeks to the end of the file, or creates a new file. 

  * FileMode.CreateNew-Specifies that the operating system should create a new file. 

  * FileMode.Truncate-Specifies that the operating system should open an existing file.  

  *      Once opened, the file should be truncated so that its size is zero bytes. 

  * FileMode.Create-Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. 

  *      System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use System.IO.FileMode.CreateNew;  

  *      otherwise, use System.IO.FileMode.Truncate. 

  * FileMode.Open-Specifies that the operating system should open an existing file. 

  * FileMode.OpenOrCreate-Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. 

  *  

  */  

IsolatedStorageFileStream isolatedFileStream =  

    new IsolatedStorageFileStream("textFiles//newText.txt", FileMode.OpenOrCreate, fileStorage);  

   

//写入  

StreamWriter fileWriter = new StreamWriter(isolatedFileStream);  

//向文件中写出内容  

fileWriter.WriteLine("write data");  

//关闭StreamWriter.  

fileWriter.Close();  

//读取  

StreamReader fileReader=new StreamReader(isolatedFileStream);  

String str=fileReader.ReadLine();  

fileReader.Close();  

//判断存储区某文件是否存,参数是文件路径  

fileStorage.FileExists("file path");  

 

补充下:WP7的开发环境,下载Microsoft Visual Studio 2010 Express For Windows Phone,安装成功后,就自带有模拟器了。操作系统应该是Windows 7,在XP下,模拟器启动有问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: