在Silverlight中还有一种叫做IsolatedStorage的存储机制,他存储信息的方式类似于我们的cookie, IsolatedStorage存储独立于每一个Silverlight的application,换句话说我们加载多个Silverlight应用程序是他们不会相互影响,我们这样就可以在silverlight 下次运行的时从IsolatedStorage中提取一些有用的数据,这对我们来说是很好的一件事吧~

使用islatedstorage也十分简单,不废话了 还是上个实例看吧.

XAML:

 
  
  1. <UserControl x:Class="SilverlightApplication10.Page" 
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Width="400" Height="300"
  5.     <Canvas x:Name="myCanvas" Background="White"
  6.         <TextBlock MouseLeftButtonDown="myTxt_MouseLeftButtonDown" Height="31" Width="119" Canvas.Left="142" Canvas.Top="139" Text="click me" TextWrapping="Wrap" x:Name="myTxt"/> 
  7.     </Canvas> 
  8. </UserControl> 

我们用IsolatedStorageFile.GetUserStoreForApplication()获取一个IsolatedStorage文件对象.

随后我们将创获取IsolatedStorageFileStream对象,再将文件已流的形式写入.

注:(using System.IO.IsolatedStorage;using System.IO;)

 
  
  1. private void SaveData(string _data, string _fileName) 
  2.         { 
  3.             using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication()) 
  4.             { 
  5.                 using (IsolatedStorageFileStream myIsfs = new IsolatedStorageFileStream(_fileName, FileMode.Create, myIsf)) 
  6.                 { 
  7.                     using (StreamWriter mySw = new StreamWriter(myIsfs)) 
  8.                     { 
  9.                         mySw.Write(_data);  
  10.                         mySw.Close(); 
  11.                     } 
  12.                 } 
  13.             } 
  14.         } 

这样我们就完成写入工作,读取也同样简单~

 
  
  1. private string LoadData(string _fileName) 
  2.         { 
  3.             string data = String.Empty; 
  4.             using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication()) 
  5.             { 
  6.                 using (IsolatedStorageFileStream myIsfs = new IsolatedStorageFileStream(_fileName, FileMode.Open, myIsf)) 
  7.                 { 
  8.                     using (StreamReader sr = new StreamReader(myIsfs)) 
  9.                     { 
  10.                         string lineOfData = String.Empty; 
  11.                         while ((lineOfData = sr.ReadLine()) != null
  12.                             data += lineOfData; 
  13.                     } 
  14.                 } 
  15.             }  
  16.             return data; 
  17.         } 

就此我们就完成了文件的读写,在此说明一点Silverlight默认分配一个application的IsolatedStorage空间是1MB.

当然我们也可以更改这个限额~ 这个问题我下次再给大家说吧~

Source codeIsolatedStorageDEMO1