zoukankan      html  css  js  c++  java
  • 【WindowsPhone】 独立存储

    1> 什么是独立存储?
          任何安装在Windows Phone 7/8中的程序都可以访问自身的永久磁盘存储区域,该区域称为独立存储。此种存储方式将提供一个磁盘存储空间,他是一种虚拟的文件系统,能存储小量的数据;在默认的情况下,它只能存储1MB的文件;用户可能根据自己的要求可以对空间的大小进行合理的分配。其数据本身还是存储在本地文件系统中的,但是其实际对于应用程序是透明的,应用程序只能够访问当前用户在当前应用程序域的文件及文件夹。
          如下图所示,每个应用程序将在独立存储中被分配一个独立的存储空间,称为应用程序数据存储文件夹,即该应用的独立存储根目录。应用程序可以调用独立存储 API 在该目录下存储数据,根据使用方式及功能的不同,独立存储空间又包含两部分(独立设置存储和独立文件存储)

       <——  应用程序独立存储空间逻辑结构 (此图源自MSDN)

    2> 设置和文件
          WP7/8没有本地数据库API可以利用,提供的有XML独立存储云存储。Isolated Storage(独立存储)有两种方式在本地存储你的数据,第一是通过库中的键/值对,叫做IsolatedStorageSettings(独立设置存储),第二是通过创建真实的文件和目录,叫做IsolatedStorageFile(独立文件存储)
      2.1>  IsolatedStorageSettings(独立设置存储)
             IsolatedStorageSettings是支持保存应用程序存储区或网站存储中的键/值对的字典集合,它自动负责序列化对象,并将其保存在独立存储中。(已序列化的对象将保存到名为_LocalSettings的独立存储中的文件中。)它以键/值对方式提供一种快速数据访问方式,主要用于存储一些应用设置信息。对外表现为一个键值对集合,可以使用兼职对集合的语法来进行操作。      

           命名空间为:System.IO.IsolatedStorage;主要涉及System.IO.IsolatedStorage.IsolatedStorageSettings类

       2.1.1>       

      //创建操作独立设置存储必须的IsolatedStorageSettings类的对象
                 IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            //添加一个键值对
                 settings.Add(key,value);    
                  或 根据key来获取相对应的value
                 settings[key]=value;
                  if(settings.Contains(key))
                   {
                       string value = settings[key].ToString();
                   }
            //读取键值对
                 string kk = (string)settings["kk"];
            //修改键值对
                 settings["kk"] = value;
            //判断该键是否存在
                 string isExist = settings.Contains("kk");
            //移除
                 settings.Remove("kk");
            //清除
                 settings.Clear();
            //保存
                 settings.Save();

             2.1.2>  以下用一个例子来说明:(源自WP7完美开发征程)    

             WP7主界面如下图 App1 所示,代码如下:

     
    ....
    using System.IO.IsolatedStorage; namespace IsolatedStorageSettings { public partial class MainPage : PhoneApplicationPage { //创建操作独立设置存储必须的IsolatedStorageSettings类的对象 IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; // 构造函数 public MainPage() { InitializeComponent(); } //为4个按钮添加ChangeSettins事件处理程序 private void ChangeSettings(object sender, RoutedEvent e) { string key = txbKey.Text.Trim(); string value = txbValue.Text; //表示按钮控件 Button ClickedButton = sender as Button; switch (ClickedButton.Name) { //添加 case "btn_Add": settings.Add(key, value); break; //修改 case "btn_Update": settings[key] = value; break; //移除指定键值对 case "btn_Remove": settings.Remove(key); break; //清除 case "btn_Clear": settings.Clear(); break; } //保存 settings.Save(); ReadAllSettings(); } //显示所有的键值对 protected void ReadAllSettings() { string message = "All Setting Key-Values:"+System.Environment.NewLine; foreach(string key in settings.Keys) { message += string.Format("{0}={1}\n",Key,settings[key].ToString()); } teblockSettings.Text = message; } }

       <—— 图App1                < —— 图App2                      

    2.2>  IsolatedStorageFile(独立文件存储)
             IsolatedStorageFile提供类似于文件系统一样的访问方式,应用程序可以以文件形式在其中存储任意数据(包括文本、图像、音视频,甚至代码文件等),如同操作常规文件系统一样创建、删除、访问文件及文件夹。
           命名空间为:System.IO.IsolatedStorage;主要涉及System.IO.IsolatedStorage.IsolatedStorageFile类。实际上,IsolatedStorage.IsolatedStorageFile类是 FileStream类 的一个子类。       
      2.2.1>   IsolatedStorageFile 常用的方法如下:
                方法名                           说明
             CreateDirectory()        创建一个新的独立存储文件夹
             DeleteDirectory()        删除独立存储文件夹       
             CreateFile()                创建文件
             DeleteFile()                删除文件                  
             GetFileNames()           得到文件名称集合
             GetDirectoryName()    得到文件夹名称集合
             OpenFile()                  打开文件
             Remove()                  移出所有的文件和文件夹 
      2.2.2> 文件读写操作的基本过程如下:
            (1)用获得的IsolatedStorageFile对象的OpenFile方法创建一个IsolatedstorageFileStream对象(或者用IsolatedstorageFileStream的构造方法构造)。
            (2)针对IsolatedstorageFileStream对象构造StreamReader或StreamWriter对象进行文件读写。
            (3)不要忘记关闭流对鞋对象以释放资源。

          示例代码1:

    //为程序获取一个虚拟的本地存储  
                IsolatedStorageFile myStorage = IsolatedStorageFile.GetUserStoreForApplication();  
              //创建一个新的文件夹,并创建一个newText.txt文档 
                myStorage.CreateDirectory("textFiles");  
                IsolatedStorageFileStream isolatedFileStream =  
                new IsolatedStorageFileStream("textFiles//newText.txt", FileMode.OpenOrCreate, fileStorage);    
              //写入数据
                StreamWriter fileWriter = new StreamWriter(isolatedFileStream);   
                fileWriter.WriteLine(newText.txt);  
              //关闭StreamWriter.  
                fileWriter.Close();  
              //读取数据 
                StreamReader fileReader=new StreamReader(isolatedFileStream);  
                String str=fileReader.ReadLine();  
                fileReader.Close();  
              //判断存储区某文件是否存在,参数是文件路径  
                fileStorage.FileExists("file path");

          也可将以上的创建和读取代码放入using语句中,更改为下面的代码

          示例代码2:

    // 创建一个新的文件夹,并创建一个newText.txt文档
          myStorage.CreateDirectory("textFiles");   
         using (var isolatedFileStream = new IsolatedStorageFileStream("textFiles//newText.txt", FileMode.OpenOrCreate, myStore))
         {
           //写入数据
             using (var fileWriter = new StreamWriter(isolatedFileStream))
             {
                 fileWriter.WriteLine(newText.txt);
             }
         }
     
         //将文字读出来,放入try..catch语句中处理异常
     
         IsolatedStorageFile myStorage = IsolatedStorageFile.GetUserStoreForApplication();
       try
         {
            // 指出具体路径
             using (var isolatedFileStream = new IsolatedStorageFileStream(textFiles//myFile.txt", FileMode.Open, myStore))
             {
                 // 读取数据
                using (var fileReader = new StreamReader(isolatedFileStream))
                 {
                     txtRead.Text = fileReader.ReadLine();
                 }
             }
          }
         catch
         {
             //当用户第一次点击Read按钮时处理异常
             txtRead.Text = "需要第一次创建文件";
         }

      2.2.3>  以下用一个例子来展示独立存储中基本的文件读写操作。(源自WP7完美开发征程)        WP7主界面如上图 App2 所示,代码如下:

     ...
     using System.IO.IsolatedStorage;
     using System.IO;
    namespace PhoneApp19 { public partial class MainPage : PhoneApplicationPage { //为程序获取一个虚拟的本地存储 IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication(); // 构造函数 public MainPage() { InitializeComponent(); } //写入数据 private void btnWrite_Click(object sender, RoutedEventArgs e) { string filePath = txbFilePath.Text.Trim(); string fileName = txbFileName.Text.Trim(); string fullFileName = System.IO.Path.Combine(filePath,fileName); string content = txbContent.Text; //判断文件是否存在,若不存在则创建 if (!storageFile.DirectoryExists(filePath)) { storageFile.CreateDirectory(filePath); } //写入 using (StreamWriter writer = new StreamWriter(storageFile.OpenFile(fullFileName, FileMode.Append))) { writer.WriteLine(content); } } //读取数据 private void btnRead_Click(object sender, RoutedEventArgs e) { string fullFilePath = txbFullFilePath.Text.Trim(); if (!storageFile.FileExists(fullFilePath)) { txbReadContent.Text = "指定文件不存在"; return; } //读取 using (StreamReader reader = new StreamReader(storageFile.OpenFile(fullFilePath, FileMode.Open))) { txbReadContent.Text = reader.ReadToEnd(); } } } }

    小技巧:
        创建命名空间时的一个快捷方式:
         当清楚属性 IsolatedStorageSettings 时,写出属性 IsolatedStorageSettings ,并输入,按住Ctrl键同时输入.即打开一个小helper窗口,在窗口中的那个小using语句高亮显示时,单机键盘上的Return或Enter键,便在页面开头部分添加了一个新的using语句,即 using System.IO.IsolateStorage

     --后记: 这是我第一次在博客园上发表文章,文章写的死板不成熟,可能也有些知识点没有涉及到,我会努力的呢,fighting!


     



       

          

  • 相关阅读:
    JSON学习笔记-5
    JSON学习笔记-4
    JSON学习笔记-3
    JSON学习笔记-2
    JSON学习笔记-1
    stm32f103各个型号芯片之间程序移植(stm32的兼容问题)
    如何找回微信小程序源码?2020年微信小程序反编译最新教程 小宇子李
    git常用命令
    304 怎么办 怎么解决 缓存解决
    微信小程序 CSS border-radius元素 overflow:hidden失效问题 iPhone ios 苹果兼容问题 伪类元素
  • 原文地址:https://www.cnblogs.com/kefira/p/WindowsPhone7.html
Copyright © 2011-2022 走看看