【发布时间】:2017-02-10 00:26:35
【问题描述】:
标题确实说明了一切。我已经坚持了好几天了,希望能得到一些帮助。我有一个主页和一个设置页面,当主页第一次加载时它测试本地文件夹中的 settings.xml 并在找不到时复制它。然后,当用户打开设置页面时,它应该从本地文件夹加载详细信息,允许用户在通过 OnNavigatedFrom 事件将它们保存回本地文件夹之前进行编辑。
从安装文件夹加载到本地文件夹的代码
// Has the file been copied already?
bool blFileExist = false;
try
{
await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
// No exception means it exists
blFileExist = true;
btnSettings.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
}
catch (System.IO.FileNotFoundException)
{
// The file obviously doesn't exist
blFileExist = false;
btnSettings.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
}
catch (Exception)
{
}
if (!blFileExist)
{
try
{
// Cant await inside catch, but this works anyway
StorageFile stopfile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("settings.xml");
await stopfile.CopyAsync(ApplicationData.Current.LocalFolder);
}
catch (System.IO.FileNotFoundException)
{
}
catch (Exception)
{
}
}
加载和保存设置页面的代码
private void loadSettings()
{
try
{
doc = XElement.Load("settings.xml");
nAIPlayers = int.Parse(doc.Element("ai_players").Value);
strCardBack = doc.Element("back").Value;
comboBoxAIPlayers.SelectedIndex = nAIPlayers - 1;
}
catch (System.IO.FileNotFoundException)
{
}
catch (Exception ex)
{
}
}
private async void saveSettings()
{
//try
//{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
doc.SetElementValue("ai_players", nAIPlayers);
doc.SetElementValue("back", "Back_0");
doc.Save(fileStream);
}
/*}
catch (System.IO.FileNotFoundException)
{
}
catch (Exception ex)
{
}*/
}
我认为问题在于我正在访问本地文件以保存它,并访问安装文件以加载它。结果是无论我保存什么它总是读取原始settings.xml中的值
如何从本地文件夹加载这个?
doc = XElement.Load("settings.xml");
更新
在第一次迭代中,代码运行良好,设置页面代码正常打开。只有在离开设置页面并运行 saveSettings() 方法后,它才会在重新加载设置页面并运行 loadSettings() 时失败并抛出错误。
System.Xml.XmlException:根级别的数据无效。第 5 行,位置 12
【问题讨论】: