I am working on a Windows 8 XAML / C # application. I am trying to download XML from Windows.Storage.ApplicationData.Current.LocalFolder to XDocument several times during the life of the application. However, I get a System.UnauthorizedAccessException when I try to load a 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); }
For debugging purposes only:
private async void Button_Click_2(object sender, RoutedEventArgs e) { XDocument TempXDoc = await LoadXmlFromLocalFolderAsync("Categories.xml"); Debug.WriteLine(TempXDoc); }
Download 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 Click events several times, an exception is thrown. There is no specific scenario. Sometimes an error occurs, sometimes it is not. Where am I going wrong? I am new to async and await things.
source share