我正在使用 visual studio 2015 为 Windows 桌面制作应用程序。
我尝试打开插入元素并保存文档,但是当我使用函数 .Save()
时,它不会保存文件
这是我的代码
String filePath = "person.xml";
if (File.Exists(filePath))
{
XDocument collection = XDocument.Load(filePath);
XElement person = new XElement("user",
new XElement("id", this.getId()),
new XElement("name", this.getName()),
new XElement("info", this.getInfo()));
collection.Element("root").Add(person);
using (var file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = file.OpenFile(filePath, FileMode.OpenOrCreate))
{
collection.Save(stream);
}
}
}
else
{
XDeclaration declaration = new XDeclaration("1.0", "utf-8", "yes");
XDocument collection = new XDocument(declaration);
XElement person = new XElement("root",
new XElement("user",
new XElement("id", this.getId()),
new XElement("name", this.getName()),
new XElement("info", this.getInfo())));
collection.Add(person);
using (var file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = file.CreateFile(filePath))
{
collection.Save(stream);
}
}
}
但是当我尝试加载文件时,出现错误,文件不存在
编辑: 加载 xml 的代码:
XDocument collection = XDocument.Load("person.xml");
foreach(XElement a in collection.Descendants("user")) {
Person temp = new Person((int)a.Element("id"), (string)a.Element("info"), (string)a.Element("name"));
lPerson.Add(temp);
lPerson.nbPerson++;
}
最佳答案
您不需要为此使用文件流。
就做一个collection.Save(filename);
编辑: 您是否打算尝试将 person.xml 文件写入 collections.xml?您正在尝试以 collection.xml 格式打开,但我看不到您以这种方式保存它的位置。
如果你只是写回文件,那么使用这个:
collection.Element("root").Add(person);
collection.Save(filepath)'
编辑#2: 如果您尝试写入独立存储,则需要采取不同的方式。这是我找到的有关如何操作的文档。
https://msdn.microsoft.com/en-us/library/cc189085%28v=vs.95%29.aspx
关于c# - XDocument.save() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34341540/