本篇 QuickStart 示例演示如何从isolated store中对文件进行管理,包括保存数据,读取数据等.
运行 查看 想要在基于Silverlight的应用程序中做到以上的功能,你需要准备以下步骤:
在isolated storage中创建一个新文件,并使用StreamWriter来对文件进行写入.
打开isolated storage中的一个文件,并使用 StreamReader来读取它.
在isolated storage中删除文件.
要求 (available from the Silverlight download site):
Microsoft Silverlight 1.1 Alpha.
Microsoft Visual Studio Code Name "Orcas" Beta 1.
Microsoft Silverlight Tools Alpha for Visual Studio Code Name "Orcas" Beta 1.
A Silverlight project. For instructions, see 怎么来创建一个Silverlight Project.
使用IsolatedStorageFile 类
IsolatedStorageFile 类抽象了isolated storage的虚拟文件系统 . 你创建一个 IsolatedStorageFile 类的实例, 你可以使用它对文件或文件夹进行列举或管理.同样你还可以使用该类的 IsolatedStorageFileStream 对象来管理文件内容.
虚拟文件系统根目录是对于每个机器当前登陆用户不同的, 它是一个隐藏的文件夹,存在于物理文件系统中. 每个application的不同标识将会使其映射到不同的文件夹中, 也就是说,将分配给每个不同的application 一个属于它的虚拟文件系统. .NET Framework version 2.0中的文件夹节构和隐藏架构同样在 .NET Framework for Silverlight中也用到了.
在isolated storage中,你必须提供绝对路径来得到文件位置 . 你不能使用一些相对路径,比如: ..\..\..\..\filename 这些在这个文件系统中是无效的.
在isolated storage中创建一个新文件,并用StreamWriter来写入
得到你的application的 user-isolated store .
CS
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
VB
Using isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
在根目录下创建 IsoStoreFile.txt 文件.
CS
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("IsoStoreFile.txt", FileMode.Create, isoStore))
VB
Using isoStream As New IsolatedStorageFileStream("IsoStoreFile.txt", FileMode.Create, isoStore)
写文件.
using (StreamWriter writer = new StreamWriter(isoStream)) { writer.Write("This is isolated storage file."); } Using writer As New StreamWriter(isoStream) writer.Write("This is isolated storage file.") End Using
你不需要调用isoStore和 isoStream和writer的Close 方法 ,因为using 申明的对象将在括号结束时自动disposed.
打开isolated storage中的一个文件,并使用StreamReader来读入内容
Open an existing isolated storage file.
CS
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("IsoStoreFile.txt", FileMode.Open, isoStore))
VB
Using isoStream As New IsolatedStorageFileStream("IsoStoreFile.txt", FileMode.Open, isoStore)
通过StreamReader来读入文件内容.
using (StreamReader reader = new StreamReader(isoStream)) { // Read the first line from the file. String sb = reader.ReadLine(); } Using reader As New StreamReader(isoStream) ' Read a line from the file. Dim sb As String = reader.ReadLine() End Using
你不需要调用reader的Close 方法,因为using 申明的对象将在括号结束时自动disposed.
从isolated storage中删除文件
调用DeleteFile() 方法.
CS
isoStore.DeleteFile("IsoStoreFile.txt");
VB
isoStore.DeleteFile("IsoStoreFile.txt")