WP7 Isolated Storage详解(4)-读写文本文件
首先创建一个Windows Phone 7项目,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:
using System.IO; using System.IO.IsolatedStorage;
我们使用类IsolatedStorageFileStream在隔离存储空间中进行读、写、创建文件的操作。这个类继承自FileStream,所以在通常使用FileStream的地方都可以使用IsolatedStorageFileStream,例如StreamReader 和 StreamWriter。
创建文本文件
示例中我们创建了一个名称为myFile.txt的文本文件,并写入了一些内容。
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.Write。FileAccess的成员共有Read、Write、ReadWrite三种。
向已存在文件写入
示例中打开了一个已存在的名称为myFile.txt的文本文件,并追加了一些内容。
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。
在目录中进行读写操作
- 写入
//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();
- 读取
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)读取前判断文件是否存在。
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架