下面是读取文件的代码:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
// Open the file for reading
stream = new IsolatedStorageFileStream("MyText.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read,isf);
// Use the stream normally in a TextReader
System.IO.TextReader reader = new System.IO.StreamReader(stream);
string sLine = reader.ReadLine();
this.tbTextsRead.Text = sLine;
reader.Close(); // Close the reader
stream.Close(); // Close the stream
而Page.xaml.cs的代码全部如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Text;
namespace WriteLocalFileInSL
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
System.IO.Stream stream;
private void btnWrite_Click(object sender, RoutedEventArgs e)
{
// Get the storage file for the application
//Step1, you need to access an IsolatedStorageFile.
//This is done by calling IsolatedStorageFile.GetUserStoreForApplication() or IsolatedStorageFile.GetUserStoreForSite().
//There are some differences between the functions, but either will get you a private file system in which you can read and write files.
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
// Open&Create the file for writing
//Step2, you need create or open your file almost as you would normally.
//Instead of using FileStream, you would use IsolatedStorageFileStream (which is derived from FileStream).
//This means that once you have your stream, you can use it anywhere you would have normally used a normal FileStream.
stream = new IsolatedStorageFileStream("MyText.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write, isf);
// Use the stream normally in a TextWriter
//Step3, you read or write as you normally would.
System.IO.TextWriter writer = new System.IO.StreamWriter(stream);
writer.WriteLine(this.tbTexts.Text.ToString());
writer.Close(); // Close the writer so data is flushed
stream.Close(); // Close the stream too
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
// Open the file for reading
stream = new IsolatedStorageFileStream("MyText.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read,isf);
// Use the stream normally in a TextReader
System.IO.TextReader reader = new System.IO.StreamReader(stream);
string sLine = reader.ReadLine();
this.tbTextsRead.Text = sLine;
reader.Close(); // Close the reader
stream.Close(); // Close the stream
}
}
}
按下F5,运行,效果如下:
正在左侧文本框输入文本内容,然后按下写入文件按钮进行保存,效果如下:

保存文件后,再按下读出文件按钮显示刚才保存的文件内容在右侧文本框内:

我们还可以运用IsolatedStorage来操作Binary和Xml类型的文件。
需要注意的是,用户可以通过Silverlight设置可以禁用这个功能