WP7-Isolated Storage详解

转自:http://www.cnblogs.com/zdave/archive/2011/05/06/2038924.html
什么是Isolated Storage?

Isolated Storage又叫做隔离存储空间,Windows Phone 7手机上用来本地存储数据。下图是一个存储应用的文件夹结构图:

IC381787

Isolated Storage用来创建与维护本地存储。WP7上的架构和Windows下的Silverlight类似,所有的读写操作都只限于隔离存储空间并且无法直接访问磁层操作系统的文件系统。这样能够防止非法的访问以及其他应用的破坏,增强安全性。

提示:如果你有两个应用想要共用一个同一个数据,则没法通过本地存储实现。你可以使用web服务等。

提示:WP7下的隔离存储空间没有配额的限制。应用应该只保存必要的数据。当Windows Phone只剩下10%的可用空间,用户会收到一个提醒并可能停止当前应用。对用户来讲这是一个很差的用户体验。

在隔离存储空间下可以进行目录操作、文件操作、应用程序配置信息等。


Isolated Storage文件和目录操作

在使用Isolated Storage之前,需要先引用两个命名空间

?
1
2
using System.IO;
using System.IO.IsolatedStorage;
目录操作
  • 创建目录

通过调用类IsolatedStorageFile实例的CreateDirectory方法即可创建目录。

?
1
2
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
myIsolatedStorage.CreateDirectory( "NewFolder" );

提示:你可以随意命名任何复杂的目录如“Folder1/Folder2/Folder3/NewFolder”

?
1
myIsolatedStorage.CreateDirectory( "Folder1/Folder2/Folder3/NewFolder" );
  • 删除目录

通过调用类IsolatedStorageFile实例的DeleteDirectory方法即可删除目录。

?
1
myIsolatedStorage.DeleteDirectory( "NewFolder" );
  • 最佳方式

-检查目录是否已存在

myIsolatedStorage.DirectoryExists(directoryName)

-使用try{}catch{}捕获异常

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void CreateDirectory( string directoryName)
  {
     try
     {
         IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
         if (! string .IsNullOrEmpty(directoryName) && !myIsolatedStorage.DirectoryExists(directoryName))
         {
           myIsolatedStorage.CreateDirectory(directoryName);
         }
     }
     catch (Exception ex)
     {
         // handle the exception
     }
}

创建一个目录只需要调用这个方法并给一个参数作为目录名称。

?
1
this .CreateDirectory( "NewFolder" );

-删除目录同样检查

提示:目录必须是空的才可以被删除。一旦删除无法恢复。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void DeleteDirectory( string directoryName)
{
     try
     {
         IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
         if (! string .IsNullOrEmpty(directoryName) && myIsolatedStorage.DirectoryExists(directoryName))
         {
             myIsolatedStorage.DeleteDirectory(directoryName);
         }
     }
     catch (Exception ex)
     {
         // handle the exception
     }
}

删除一个目录只需要调用这个方法。

?
1
this .DeleteDirectory( "NewFolder" );
提示:目前在隔离存储空间无法重命名目录。
文件操作
  • 创建文件

通过使用StreamWriter可以像这样创建文件:

?
1
2
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "NewFolder\\SomeFile.txt" , FileMode.CreateNew, myIsolatedStorage));

提示:如果不给出任何路径,文件将会被创建在根目录下。另外也可以用IsolatedStorageFileStream创建文件:

?
1
IsolatedStorageFileStream stream1 = new IsolatedStorageFileStream( "SomeTextFile.txt" , FileMode.Create, myIsolatedStorage);
  • 删除文件

通过调用类IsolatedStorageFile实例的DeleteFile方法即可删除文件。

?
1
myIsolatedStorage.DeleteFile( "NewFolder/SomeFile.txt" );
  • 最佳方式

-检查你将创建的文件的所在路径是否存在

myIsolatedStorage.DirectoryExists(directoryName)

-检查你将创建的文件是否存在myIsolatedStorage.FileExists(filePath)。如果存在你需要在创建前先删除已有的文件。

-使用try{}catch{}捕获异常

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
try
{
     IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
     StreamWriter writeFile;
     if (!myIsolatedStorage.DirectoryExists( "NewFolder" ))
     {
         myIsolatedStorage.CreateDirectory( "NewFolder" );
         writeFile = new StreamWriter( new IsolatedStorageFileStream( "NewFolder\\SomeFile.txt" , FileMode.CreateNew, myIsolatedStorage));
     }
     else
     {
         writeFile = new StreamWriter( new IsolatedStorageFileStream( "NewFolder\\SomeFile.txt" , FileMode.CreateNew, myIsolatedStorage));
     }
      
}
catch (Exception ex)
{
     // do something with exception
}
提示:要完全删除隔离存储空间的内容,调用类IsolatedStorageFile实例的Remove方法即可。
?
1
myIsolatedStorage.Remove();

应用程序配置信息IsolatedStorageSettings

首先创建一个Windows Phone 7项目,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:

?
1
using System.IO.IsolatedStorage;

向WP7隔离存储空间中存储数据最简单的方式就是通过类IsolatedStorageSettings。其实是隔离存储空间里面的Dictionary<TKey, TValue>,一般用于简单的配置信息,例如有key和value的对应。

提示:IsolatedStorageSettings只支持key/value这种对应格式。

通过IsolatedStorageSettings存储字符串

存储一个字符串代表邮箱:

?
1
2
3
4
5
public void SaveStringObject()
{
     var settings = IsolatedStorageSettings.ApplicationSettings;
     settings.Add( "myemail" , "myemail@zdave.net" );
}
通过IsolatedStorageSettings读取字符串

读取刚才存储的邮箱:

?
1
var email= settings[ "myemail" ] as string ;
通过IsolatedStorageSettings存储复杂对象

这个示例将演示如何存储复杂对象。首先创建一个简单的类City,然后通过IsolatedStorageSettings存储。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void SaveCompositeObject()
{
     var settings = IsolatedStorageSettings.ApplicationSettings;
     City city = new City { Name = "London" , Flag = "uk.png" };
     settings.Add( "city" , city);
}
  
public class City
{
     public string Name
     {
         get ;
         set ;
     }
  
     public string Flag
     {
         get ;
         set ;
     }
}
通过IsolatedStorageSettings读取复杂对象

读取上面存储的City信息:

?
1
2
City City1;
settings.TryGetValue<City>( "city" , out City1);
IsolatedStorageSettings与数据绑定

这个示例将展示如何通过IsolatedStorageSettings数据绑定到刚才的City信息:

?
1
2
<TextBlock Text= "{Binding Name}" FontSize= "50" />
<Image Source= "{Binding Flag}" Stretch= "None" HorizontalAlignment= "Left" />
?
1
2
3
4
City City1;
settings.TryGetValue<City>( "city" , out City1);
  
this .DataContext = City1;

效果如下:

IsolatedStorageSettingsdatabinding

最佳方式

在尝试读取一个对象之前检查目标是否存在。

?
1
2
3
4
if (settings.Contains( "myemail" ))
{
...
}

读写文本文件

首先创建一个Windows Phone 7项目,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:

?
1
2
using System.IO;
using System.IO.IsolatedStorage;

我们使用类IsolatedStorageFileStream在隔离存储空间中进行读、写、创建文件的操作。这个类继承自FileStream,所以在通常使用FileStream的地方都可以使用IsolatedStorageFileStream,例如StreamReader 和 StreamWriter

创建文本文件

示例中我们创建了一个名称为myFile.txt的文本文件,并写入了一些内容。

?
1
2
3
4
5
6
7
8
9
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
  
//create new file
using (StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "myFile.txt" , FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
     string someTextData = "This is some text data to be saved in a new text file in the IsolatedStorage!" ;
     writeFile.WriteLine(someTextData);
     writeFile.Close();
}

提示:创建文件使用FileMode.Create,写入内容使用FileAccess.WriteFileAccess的成员共有Read、Write、ReadWrite三种。

向已存在文件写入

示例中打开了一个已存在的名称为myFile.txt的文本文件,并追加了一些内容。

?
1
2
3
4
5
6
7
8
9
10
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
  
//Open existing file
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile( "myFile.txt" , FileMode.Open, FileAccess.Write);
using (StreamWriter writer = new StreamWriter(fileStream))
{
     string someTextData = "Some More TEXT Added:  !" ;
     writer.Write(someTextData);
     writer.Close();
}

提示:打开已存在文件使用FileMode.Open,读取内容使用FileAccess.Read。

在目录中进行读写操作
  • 写入
?
1
2
3
4
5
6
7
8
9
10
11
12
//Obtain the virtual store for application
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
  
//Create a new folder and call it "ImageFolder"
myIsolatedStorage.CreateDirectory( "TextFilesFolder" );
  
//Create a new file and assign a StreamWriter to the store and this new file (myFile.txt)
//Also take the text contents from the txtWrite control and write it to myFile.txt
StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "TextFilesFolder\\myNewFile.txt" , FileMode.OpenOrCreate, myIsolatedStorage));
string someTextData = "This is some text data to be saved in a new text file in the IsolatedStorage!" ;
writeFile.WriteLine(someTextData);
writeFile.Close();
  • 读取
?
1
2
3
4
5
6
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile( "TextFilesFolder\\myNewFile.txt" , FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
     this .text1.Text = reader.ReadLine();
}
最佳方式

1)当进行文件操作的时候始终使用using关键字,using结束后会隐式调用Disposable方法,清理非托管资源。

2)检查将要进行读写操作的文件所在目录是否存在。

3)读取前判断文件是否存在。


通过XmlSerializer读写XML文件


首先创建一个Windows Phone 7项目,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:

?
1
2
3
4
using System.Xml;
using System.Xml.Serialization;
using System.IO.IsolatedStorage;
using System.IO;

提示:你需要在项目中添加System.Xml.Serialization引用。

对于很多应用,向隔离存储空间读写XML文件是很常见的任务。

一般情况下我们使用类IsolatedStorageFileStream进行读、写、创建文件等操作。与使用XmlWriter不同的是,XmlSerializer使我们更方便的在Object和XML文档之间进行序列化与反序列化转换。

本篇中我们将使用如下的Person类来生成XML文件结构:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Person
{
     string firstname;
     string lastname;
     int age;
  
     public string FirstName
     {
         get { return firstname; }
         set { firstname = value; }
     }
  
     public string LastName
     {
         get { return lastname; }
         set { lastname = value; }
     }
  
     public int Age
     {
         get { return age; }
         set { age = value; }
     }
}

将要被序列化的数据对象:

?
1
2
3
4
5
6
7
8
private List<Person> GeneratePersonData()
{
     List<Person> data = new List<Person>();
     data.Add( new Person() { FirstName = "Kate" , LastName = "Brown" , Age = 25 });
     data.Add( new Person() { FirstName = "Tom" , LastName = "Stone" , Age = 63 });
     data.Add( new Person() { FirstName = "Michael" , LastName = "Liberty" , Age = 37 });
     return data;
}
使用XmlSerializer 保存XML文件到隔离存储空间

示例中创建了一个名为People.xml的XML文件并写入数据。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Write to the Isolated Storage
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true ;
  
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
     using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile( "People.xml" , FileMode.Create))
     {
         XmlSerializer serializer = new XmlSerializer( typeof (List<Person>));
         using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
         {
             serializer.Serialize(xmlWriter, GeneratePersonData());
         }
     }
}

提示:创建文件使用FileMode.Create,写入内容使用FileAccess.WriteFileAccess的成员共有Read、Write、ReadWrite三种。

使用XmlSerializer从隔离存储空间中读取XML文件

示例中打开了一个已存在的文件People.xml并读取它的内容。然后把数据显示在一个ListBox上。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try
{
     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile( "People.xml" , FileMode.Open))
         {
             XmlSerializer serializer = new XmlSerializer( typeof (List<Person>));
             List<Person> data = (List<Person>)serializer.Deserialize(stream);
             this .listBox.ItemsSource = data;
         }
     }
}
catch
{
     //add some code here
}

提示:打开已存在文件使用FileMode.Open,读取内容使用FileAccess.Read。

?
1
2
3
4
5
6
7
8
9
10
11
< ListBox x:Name = "listBox" >
     < ListBox.ItemTemplate >
         < DataTemplate >
             < StackPanel Margin = "10" >
                 < TextBlock Text = "{Binding FirstName}" />
                 < TextBlock Text = "{Binding LastName}" />
                 < TextBlock Text = "{Binding Age}" />
             </ StackPanel >
         </ DataTemplate >
     </ ListBox.ItemTemplate >
</ ListBox >

提示:当进行文件操作的时候始终使用using关键字,using结束后会隐式调用Disposable方法,清理非托管资源。

通过XmlWriter读写XML文件

首先创建一个Windows Phone 7项目,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:

?
1
2
3
using System.Xml;
using System.IO.IsolatedStorage;
using System.IO;
使用XmlWriter 保存XML文件到隔离存储空间

示例中创建了一个名为People2.xml的XML文件并写入数据。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
     using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream( "People2.xml" , FileMode.Create, myIsolatedStorage))
     {
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.Indent = true ;
         using (XmlWriter writer = XmlWriter.Create(isoStream, settings))
         {
  
             writer.WriteStartElement( "p" , "person" , "urn:person" );
             writer.WriteStartElement( "FirstName" , "" );
             writer.WriteString( "Kate" );
             writer.WriteEndElement();
             writer.WriteStartElement( "LastName" , "" );
             writer.WriteString( "Brown" );
             writer.WriteEndElement();
             writer.WriteStartElement( "Age" , "" );
             writer.WriteString( "25" );
             writer.WriteEndElement();
             // Ends the document
             writer.WriteEndDocument();
             // Write the XML to the file.
             writer.Flush();
         }
     }
}
使用StreamReader从隔离存储空间中读取XML文件

示例中打开了一个已存在的文件People2.xml并读取它的内容。然后把数据显示在一个TextBlock 上。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
try
{
     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile( "People2.xml" , FileMode.Open);
         using (StreamReader reader = new StreamReader(isoFileStream))
         {
             this .tbx.Text = reader.ReadToEnd();
         }
     }
}
catch
{ }
提示:当进行文件操作的时候始终使用 using 关键字, using 结束后会隐式调用Disposable方法,清理非托管资源。

读取、保存图片文件

首先创建一个Windows Phone 7项目,在项目中添加一个图片例如“logo.jpg”,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:

?
1
2
3
4
5
6
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Resources;
using Microsoft.Xna.Framework.Media;
using Microsoft.Phone.Tasks;

提示:Microsoft.Xna.Framework.Media;仅当你要把图片保存到媒体库的时候才需要添加引用。

对于很多应用,向隔离存储空间读取、保存图片文件是很常见的任务。在WP7中,你还可以保存、读取媒体库中的图片。

一般情况下我们使用类IsolatedStorageFileStream进行读、写、创建文件等操作。对于图片,最大的不同就是使用类BitmapImage和类WriteableBitmap.

保存图片到隔离存储空间

示例中首先检查文件是否已经存在,然后把图片保存到隔离存储空间(转换WriteableBitmap对象到JPEG stream)。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
String tempJPEG = "logo.jpg" ;
 
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
     if (myIsolatedStorage.FileExists(tempJPEG))
     {
         myIsolatedStorage.DeleteFile(tempJPEG);
     }
 
     IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
 
     StreamResourceInfo sri = null ;
     Uri uri = new Uri(tempJPEG, UriKind.Relative);
     sri = Application.GetResourceStream(uri);
 
     BitmapImage bitmap = new BitmapImage();
     bitmap.SetSource(sri.Stream);
     WriteableBitmap wb = new WriteableBitmap(bitmap);
 
     // Encode WriteableBitmap object to a JPEG stream.
     Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
 
     fileStream.Close();
}

提示:你也可以使用WriteableBitmap来保存图片:wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

从隔离存储空间读取图片

示例中首先从隔离存储空间打开了一个名为logo.jpg的图片,并在一个Image控件中呈现出来。

?
1
2
3
4
5
6
7
8
9
10
11
12
BitmapImage bi = new BitmapImage();
  
             using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
             {
                 using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile( "logo.jpg" , FileMode.Open, FileAccess.Read))
                 {
                     bi.SetSource(fileStream);
                     this .img.Height = bi.PixelHeight;
                     this .img.Width = bi.PixelWidth;
                 }
             }
             this .img.Source = bi;

提示:“img”是一个在MainPage.xaml中的图片控件:<Image x:Name="img"/>

保存图片到手机媒体库

访问MediaLibrary需要在项目中添加引用:Microsoft.XNA.Framework。

示例中从隔离存储空间中读取一个图片,然后保存到手机的媒体库中。

?
1
2
3
4
5
6
7
8
9
10
11
12
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
             {
                 using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile( "logo.jpg" , FileMode.Open, FileAccess.Read))
                 {
                     MediaLibrary mediaLibrary = new MediaLibrary();
                     Picture pic = mediaLibrary.SavePicture( "SavedLogo.jpg" , fileStream);
                     fileStream.Close();
                 }
             }
  
             PhotoChooserTask photoChooserTask = new PhotoChooserTask();
             photoChooserTask.Show();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值