问题
So I'm trying to do the simple task of opening an XML file, adding and XElement to it, and saving it. My curent code doesn't work:
Uri dataUri = new Uri("ms-appx:///XML Files/Pinouts.xml");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
using (var stream = await file.OpenStreamForWriteAsync())
{
XDocument doc = XDocument.Load(stream);
doc.Add(new XElement(XElement.Parse(CurrentPinOut)));
doc.Save(stream);
stream.Flush();
}
As I get an "Access denied" error. I'm guessing it's a simple fix, but I haven't found anything in the last hour of searching. Any ideas?
回答1:
You cannot write files to InstalledLocation - it's read-only, but you surely can write files to LocalFolder (or other accessible locations):
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Pinouts.xml", CreationCollisionOption.GenerateUniqueName);
using (var stream = await file.OpenStreamForWriteAsync())
{
XDocument doc = XDocument.Load(stream);
doc.Add(new XElement(XElement.Parse(CurrentPinOut)));
doc.Save(stream);
stream.Flush();
}
More info about application data you will find at MSDN.
来源:https://stackoverflow.com/questions/35090648/save-and-xdocument-to-a-file-in-a-using-stream