我在使用IsolatedStorageFileStream时遇到了一个很顽固的异常“Operation not permitted on IsolatedStorageFileStream.”至今没办法找到。大侠求助
异常截图
代码如下
Student.cs
public class Student
{
public string EMail { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Student(string FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.EMail = FirstName + "@" + LastName + ".com";
}
public Student(XElement xElement)
{
this.FirstName = xElement.Attribute("FirstName").Value;
this.LastName = xElement.Attribute("LastName").Value;
this.EMail = xElement.Attribute("EMail").Value;
}
public XElement Information
{
get
{
return new XElement("Student", new XAttribute("EMail", EMail), new XElement("FirstName", FirstName), new XElement("LastName", LastName));
}
}
}
StudentList .cs
public class StudentList : List<Student>
{
public void Load(string strXMLFile)
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
XDocument doc = null;
IsolatedStorageFileStream isfStream = null;
if (isfData.FileExists(strXMLFile))
{
isfStream = new IsolatedStorageFileStream(strXMLFile, System.IO.FileMode.Open,FileAccess.Write, isfData);
doc = XDocument.Load(isfStream);
isfStream.Close();
}
else
{
doc = XDocument.Load(strXMLFile);
isfStream = new IsolatedStorageFileStream(strXMLFile, System.IO.FileMode.CreateNew, FileAccess.Write, isfData);
doc.Save(isfStream);
isfStream.Close();
}
var vStudent = from s in doc.Descendants("Student") select new Student(s);
this.Clear();
AddRange(vStudent);
}
public void Save(string strXMLFile)
{
try
{
XElement xml = new XElement("Students", from p in this select p.Information);
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(
strXMLFile,
System.IO.FileMode.Open,
IsolatedStorageFile.GetUserStoreForApplication());
xml.Save(isfStream);
isfStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Students.xml
<?xml version="1.0" encoding="utf-8" ?>
<Students>
<Student EMail="Woo@Jianqiang.com">
<FirstName>Woo</FirstName>
<LastName>Jianqiang</LastName>
</Student>
<Student EMail="Whitcomb@Donald.com">
<FirstName>Whitcomb</FirstName>
<LastName>Donald</LastName>
</Student>
<Student EMail="Kadi@Wadad.com">
<FirstName>Kadi</FirstName>
<LastName>Wadad</LastName>
</Student>
</Students>
Mainpage.xaml
<ListBox x:Name="lbData"></ListBox>
Mainpage.cs
public partial class MainPage : PhoneApplicationPage
{
StudentList data =null;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void loadData() {
data = new StudentList();
data.Load("Model/Students.xml");
lbData.ItemsSource = data;
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
loadData();
}