我一直在處理將配置加載和寫入XML文件的應用程序。我知道這樣做有一些意見,但我一直在這個代碼有問題。保存XML文件似乎只能保存一個條目
private static void AddToXmlTemplate(Template tmp, string _config)
{
string configFile = _config + "configuredTemplate.xml";
FileStream fs = new FileStream(configFile, FileMode.OpenOrCreate);
if (File.Exists(configFile)) {
XDocument xD = new XDocument();
xD.Add(new XElement("Store",
new XElement("template",
new XElement("filePath", tmp.TempPath),
new XElement("Name", tmp.TempName),
new XElement("description", tmp.TempDesc))));
xD.Save(fs);
fs.Flush();
fs.Dispose();
//commenting for change to allow sync.
}
else
{
/********------ appends the template to the config file.------*************/
XDocument xD = XDocument.Load(fs);
XElement root = xD.Element("Store");
IEnumerable<XElement> rows = root.Descendants("template");
XElement last = rows.Last();
last.AddAfterSelf(
new XElement("template"),
new XElement("filePath", tmp.TempPath),
new XElement("Name", tmp.TempName),
new XElement("description", tmp.TempDesc));
xD.Save(fs);
fs.Flush();
fs.Dispose();
}
}
這整個函數被調用另一個函數foreach循環,並且所有的功能應是檢查,看看是否有文件夾中的配置文件,檢查HTML文件,要求用戶提供信息關於這些文件,然後保存到XML文件中。
我在想,我需要將文件流操作,也可能是XDocument移動到調用函數,並將它們傳遞給這個。
最大的問題是它只保存最後一組節點。
我可以看到這應該如何工作,但是如果我們進行這些更改,它只會運行else塊。 –
@ChrisRutherford可能與文件路徑有關。嘗試使用字符串configFile = Path.Combine(_config,「configuredTemplate.xml」) – daniell89