我使用可观察集合在我的应用程序中保存列表,并使用XML将该列表保存到独立存储。当我添加项目时,应用程序是可以的,但是当我删除项目并重新启动应用程序时,它无法读取XML。我使用i工具从隔离存储中获取XML,是的,它的结构是错误的。
这是代码
public void saveToXML()
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
XmlWriterSettings xmlWriterSetting = new XmlWriterSettings();
xmlWriterSetting.Indent = true;
using (storage)
{
using (IsolatedStorageFileStream fsIdea = new IsolatedStorageFileStream("Idea.xml", FileMode.OpenOrCreate, storage))
{
using (XmlWriter xWIdea = XmlWriter.Create(fsIdea, xmlWriterSetting))
{
XmlSerializer xSIdea = new XmlSerializer(typeof(ObservableCollection<IdeaViewModel>));
xSIdea.Serialize(xWIdea, App.ViewModel.ItemsIdea);
}
}
}
}
public void readFromXML()
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
if (!storage.FileExists("Idea.xml") )
{
saveToXML();
}
using (storage)
{
using (IsolatedStorageFileStream fsIdea = new IsolatedStorageFileStream("Idea.xml", FileMode.Open, storage))
{
XmlSerializer xSIdea = new XmlSerializer(typeof(ObservableCollection<IdeaViewModel>));
App.ViewModel.ItemsIdea = xSIdea.Deserialize(fsIdea) as ObservableCollection<IdeaViewModel>;
}
}
}
这是错误的XML文件,当我删除项目并重新启动应用程序时,错误在第9行,看起来XML文件仍然保留已删除项目的一部分?
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfIdeaViewModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<IdeaViewModel>
<IdeaContent>sdfsd</IdeaContent>
</IdeaViewModel>
<IdeaViewModel>
<IdeaContent>sdfds</IdeaContent>
</IdeaViewModel>
</ArrayOfIdeaViewModel>aContent>sf</IdeaContent>
</IdeaViewModel>
<IdeaViewModel>
<IdeaContent>sdfsd</IdeaContent>
</IdeaViewModel>
<IdeaViewModel>
<IdeaContent>sdfds</IdeaContent>
</IdeaViewModel>
</ArrayOfIdeaViewModel>
(我把readFromXML()放在app的构造函数中,saveToXML()放在这里
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
saveToXML();
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
// Ensure that required application state is persisted here.
saveToXML();
}
答案 0 :(得分:0)
保存时使用FileMode.Create instead of FileMode.OpenOrCreate:
using (IsolatedStorageFileStream fsIdea = new IsolatedStorageFileStream("Idea.xml", FileMode.Create, storage))
在你的情况下,你只是编辑旧版本的文件,因此你可能有一些文物。