I am working on Windows 8 XAML/C# store app. I am trying to load XML from Windows.Storage.ApplicationData.Current.LocalFolder
to XDocument
multiple times during the lifetime of the app. However, I receive System.UnauthorizedAccessException
when I try to load the file. Here are my methods:
To add to 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);
}
Just for debugging purposes:
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
XDocument TempXDoc = await LoadXmlFromLocalFolderAsync("Categories.xml");
Debug.WriteLine(TempXDoc);
}
Load and Save methods:
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();
}
If I fire the Click
events repeatedly, the exception is thrown. There's no specific scenario. Sometimes error occurs, sometimes it doesn't. Where am I going wrong? I'm pretty new with the async
and await
stuff.