我正在开发 Windows 8 XAML/C# 商店应用程序。我试图在应用程序的生命周期内多次加载Windows.Storage.ApplicationData.Current.LocalFolder
XML XDocument
。System.UnauthorizedAccessException
但是,当我尝试加载文件时收到。这是我的方法:
要添加到 XML:
private async void AddCategoryButton_Click(object sender, RoutedEventArgs e)
{
XDocument CategoryListXDoc = await LoadXmlFromLocalFolderAsync("Categories.xml");
CategoryListXDoc.Element("CategoryList").Add(
new XElement("Category", new XAttribute("Id", Guid.NewGuid()), AddCategoryTextBox.Text));
SaveXDocToLocalFolderAsync("Categories.xml", CategoryListXDoc);
}
仅用于调试目的:
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
XDocument TempXDoc = await LoadXmlFromLocalFolderAsync("Categories.xml");
Debug.WriteLine(TempXDoc);
}
加载和保存方法:
private async Task<XDocument> LoadXmlFromLocalFolderAsync(string FileName)
{
var LocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile CategoryListFile = await LocalFolder.GetFileAsync(FileName);
var stream = await CategoryListFile.OpenStreamForReadAsync() as Stream;
XDocument TempXDoc = XDocument.Load(stream);
stream.Flush();
return TempXDoc;
}
private async void SaveXDocToLocalFolderAsync(string Filename, XDocument XDocToSave)
{
var LocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile CategoryListFile = await LocalFolder.CreateFileAsync(Filename, CreationCollisionOption.ReplaceExisting);
var stream = await CategoryListFile.OpenStreamForWriteAsync() as Stream;
XDocToSave.Save(stream);
stream.Flush();
}
如果我Click
反复触发事件,则会引发异常。没有具体的场景。有时会发生错误,有时不会。我哪里错了?我对这些东西很async
陌生await
。