使用 IsolatedStorageFileStream 存储信息

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

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

XAML:

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

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

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

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

 

private void SaveData(string _data, string _fileName)
        
{
            
using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication())
            
{
                
using (IsolatedStorageFileStream myIsfs = new IsolatedStorageFileStream(_fileName, FileMode.Create, myIsf))
                
{
                    
using (StreamWriter mySw = new StreamWriter(myIsfs))
                    
{
                        mySw.Write(_data); 
                        mySw.Close();
                    }

                }

            }

        }

 

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

 

private string LoadData(string _fileName)
        
{
            
string data = String.Empty;
            
using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication())
            
{
                
using (IsolatedStorageFileStream myIsfs = new IsolatedStorageFileStream(_fileName, FileMode.Open, myIsf))
                
{
                    
using (StreamReader sr = new StreamReader(myIsfs))
                    
{
                        
string lineOfData = String.Empty;
                        
while ((lineOfData = sr.ReadLine()) != null)
                            data 
+= lineOfData;
                    }

                }

            }
 
            
return data;
        }

 

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

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

Source codeIsolatedStorageDEMO1

posted @ 2008-07-19 11:12  王博_Nick  Views(3259)  Comments(1Edit  收藏  举报