WP7 Isolated Storage详解(6)-通过XmlWriter读写XML文件
首先创建一个Windows Phone 7项目,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:
using System.Xml; using System.IO.IsolatedStorage; using System.IO;
使用XmlWriter 保存XML文件到隔离存储空间
示例中创建了一个名为People2.xml的XML文件并写入数据。
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("People2.xml", FileMode.Create, myIsolatedStorage)) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(isoStream, settings)) { writer.WriteStartElement("p", "person", "urn:person"); writer.WriteStartElement("FirstName", ""); writer.WriteString("Kate"); writer.WriteEndElement(); writer.WriteStartElement("LastName", ""); writer.WriteString("Brown"); writer.WriteEndElement(); writer.WriteStartElement("Age", ""); writer.WriteString("25"); writer.WriteEndElement(); // Ends the document writer.WriteEndDocument(); // Write the XML to the file. writer.Flush(); } } }
使用StreamReader从隔离存储空间中读取XML文件
示例中打开了一个已存在的文件People2.xml并读取它的内容。然后把数据显示在一个TextBlock 上。
try { using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("People2.xml", FileMode.Open); using (StreamReader reader = new StreamReader(isoFileStream)) { this.tbx.Text = reader.ReadToEnd(); } } } catch { }提示:当进行文件操作的时候始终使用using关键字,using结束后会隐式调用Disposable方法,清理非托管资源。
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架